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
 SQL Server 2008 Forums
 Transact-SQL (2008)
 sql max function

Author  Topic 

MH
Starting Member

8 Posts

Posted - 2014-05-21 : 15:45:10
I have a table "test"
which is like
name value
a 1
a 4
b 2
b 6
c 1

I want to get max and second max value per name
I wrote the query

select name,MAX(value)
from test
group by name

I got the result

name value
a 4
b 6
c 1

but I want
a 4 1
b 6 2
c 1

Please guide.
Thanks

TG
Master Smack Fu Yak Hacker

6065 Posts

Posted - 2014-05-21 : 16:02:32
Here's one way:

;with test (name, value)
as
(
select 'a', 1 union all
select 'a', 4 union all
select 'b', 2 union all
select 'b', 6 union all
select 'c', 1
)

select name
,[1] as Max1
,[2] as Max2
from (
select *
from (
select name
, value
, rn = row_number() over (partition by name order by value desc)
from test
) d
where rn < 3
) d (name, value, rn)
pivot (
max([value])
for [rn] in ([1],[2])
) p

output:

name Max1 Max2
---- ----------- -----------
a 4 1
b 6 2
c 1 NULL


Be One with the Optimizer
TG
Go to Top of Page

MH
Starting Member

8 Posts

Posted - 2014-05-22 : 00:43:43
Thanks, Is there any other way without using pivot?
Go to Top of Page

MuralikrishnaVeera
Posting Yak Master

129 Posts

Posted - 2014-05-22 : 01:10:52
Why not we can ....
Try following way......

-------Create your test table---------------------------------
CREATE TABLE test (name varchar(50),value int)
INSERT INTO test
select 'a', 1 union all
select 'a', 4 union all
select 'b', 2 union all
select 'b', 6 union all
select 'c', 1
-------Select First maximum value ------------------------
SELECT * INTO #temp
FROM(SELECT name
,MAX(value) AS FirstMax
FROM test
GROUP BY name
) a
----Disired result set-----------------------------------
SELECT t.Name
,t.FirstMax
,CASE WHEN EXISTS (SELECT 1 FROM test WHERE value = t.FirstMax) THEN (SELECT MAX(value) FROM test WHERE value <t.FirstMax AND name = t.Name)
END AS SecondMax
FROM #temp t
-----Drop Tables---------------------------------------
DROP TABLE test
DROP TABLE #temp
------------------------------------------------------





---------------
Murali Krishna

You live only once ..If you do it right once is enough.......
Go to Top of Page

MH
Starting Member

8 Posts

Posted - 2014-05-22 : 01:25:51
Thanks
Go to Top of Page
   

- Advertisement -