Please start any new threads on our new site at https://forums.sqlteam.com. We've got lots of great SQL Server experts to answer whatever question you can come up with.

 All Forums
 General SQL Server Forums
 New to SQL Server Programming
 question about using max

Author  Topic 

piulitza
Starting Member

1 Post

Posted - 2012-04-06 : 11:17:07
I have one table called Students with fields CodS, Name.
And another table called Marks which references to Students using CodS. In the table with Marks i have the fields: CodS and Taxes.
I need to show the name of the student which has to pay the max tax.
I tried like this:


select Name, max(Tax) as Number
from Student Inner join Marks on Student.CodS = Marks.CodS
group by Name, CodS;


The problem is this one shows all students with the max tax he has to pay ... but i need to show only the student with max tax. How can i do that?

sunitabeck
Master Smack Fu Yak Hacker

5155 Posts

Posted - 2012-04-06 : 12:55:59
You can pick the top 1 as in:
select TOP (1) Name, max(Tax) as Number
from Student Inner join Marks on Student.CodS = Marks.CodS
group by Name, CodS
Order by MAX(Tax) DESC;
You can go one step further and remove the max function (along with the group by clause) altogether if you like.
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2012-04-06 : 15:12:16
if you've multiple students with same maximum tax value you need small tweak to get all of them


select TOP (1) WITH TIES Name, max(Tax) as Number
from Student Inner join Marks on Student.CodS = Marks.CodS
group by Name, CodS
Order by MAX(Tax) DESC


------------------------------------------------------------------------------------------------------
SQL Server MVP
http://visakhm.blogspot.com/

Go to Top of Page
   

- Advertisement -