Site Sponsored By: SQLDSC - SQL Server Desired State Configuration
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.
I have a table of following type data...Col1 Col2 Col3111 1 xxx111 2 yyy111 3 zzz222 1 abc222 2 def333 0 aaa333 1 bbbI need to write an query tp extract all data rows with the max(Col2) value for corresponsing Col1 e.g. query should retrieve the following rows in this case...111 3 zzz222 2 def333 1 bbbCan someone please assist with this??? I need this a bit quick, any assistance is appreciated. Thanks.
TG
Master Smack Fu Yak Hacker
6065 Posts
Posted - 2008-04-03 : 19:56:34
>>I need this a bit quickAre you taking an exam?
select col1, col2, col3from ( select col1, col2, col3, row_number() over (partion by col1 order by col2 desc) as rn ) dwhere rn = 1
Be One with the OptimizerTG
tkizer
Almighty SQL Goddess
38200 Posts
Posted - 2008-04-03 : 19:59:07
I'd handle it like this:SELECT Col1, Col2, Col3FROM YourTable tINNER JOIN (SELECT Col1, MAX(Col2) AS Col2 FROM YourTable GROUP BY Col1) dON t.Col1 = d.Col1 AND t.Col2 = d.Col2Tara KizerMicrosoft MVP for Windows Server System - SQL Serverhttp://weblogs.sqlteam.com/tarad/
Thank you folks... I really appreciate. Have a good night!
raky
Aged Yak Warrior
767 Posts
Posted - 2008-04-04 : 07:13:34
SELECT T1.COL1,T1.COL2,T1.COL3 FROM TABLENAME T1 WHERE T1.COL2 = ( SELECT TOP 1 T2.COL2 FROM TABLENAME T2 WHERE T1.COL1= T2.COL1 ORDER BY T2.COL2 DESC)