Click here to Skip to main content
15,896,432 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hello!
Let's say I have two tables like this
tablea

people|trees
------|-----
jen | 2
mary | 4
john | 5
jen | 7
mary | 10

tableb

people|surname
--------------
mary |hue
jen |apple
john |orange

Now I want the max of the sum for the trees they have and I want to select the winner's surname and number of trees.

and I am like

SQL
SELECT  b.surname, a.people, sum(trees)
FROM tablea AS a INNER JOIN tableb AS b
WHERE a.people=b.people


And it always shows the correct amount of trees but with jen's name(the first entry).
What am I doing wrong?
Thank you!
Posted
Comments
j snooze 10-Jun-14 17:24pm    
Where is your group by clause? I don't see a max anywhere in your query?
You can at least get the sum of trees per person by adding
"Group By b.surname, a.people" to the end of your query.
HopefullyCoder 10-Jun-14 17:31pm    
I know that. I want only one person with the total max of trees.
If I have max(trees) it shows the max amount of trees in an entry and still it's on jen's name!

Ah you want to sum the trees per person, then get who has the most. Sorry, late in the day for me. Here's just one way to do it. There are more, but this will get you the person with the most trees.
(I'm assuming thats what you want?) I made temp tables called #tree and #people instead of tablea and tableb.

--Solution 1
select a.people,b.surname,a.trees
From (Select top 1 people,SUM(trees) as trees
      from #tree
      Group by people
      Order by SUM(trees) desc) a
join #people b
on a.people = b.people  
 
Share this answer
 
SQL
SELECT TOP 1
  b.surname,
  a.people,
  SUM(a.trees)
FROM
  tablea AS a
  INNER JOIN tableb AS b ON a.people = b.people
GROUP BY
  b.surname,
  a.people
ORDER BY
  SUM(a.trees) DESC


Adding some integer primary keys in there would bring it query performance. Joining two tables on a string field is a terrible habit.
 
Share this answer
 
Comments
HopefullyCoder 10-Jun-14 20:53pm    
I have a problem with "SELECT TOP 1", it's in underlined as wrong
HopefullyCoder 10-Jun-14 21:03pm    
fixed it with adding limit 1!thanks!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900