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 2005 Forums
 Transact-SQL (2005)
 find max for each id.

Author  Topic 

whitebird
Starting Member

12 Posts

Posted - 2008-02-13 : 12:21:41
hi,
i have values like this.

1 10
1 60
1 70
2 60
2 10
2 20
3 30
3 10
3 50

i need a query to print the like this.
1 70
2 60
3 50

please help me out.
regards,
Raghu sunkara.

Raghu sunkara.

SwePeso
Patron Saint of Lost Yaks

30421 Posts

Posted - 2008-02-13 : 12:24:36
SELECT Col1, Max(Col2) FROM Table1 GROUP BY Col1 ORDER BY Col1



E 12°55'05.25"
N 56°04'39.16"
Go to Top of Page

visakh16
Very Important crosS Applying yaK Herder

52326 Posts

Posted - 2008-02-13 : 12:38:39
or use ROW_NUMBER() function:-

SELECT t.Col1,
t.Col2
FROM
(
SELECT ROW_NUMBER() OVER(PARTITION BY Col1 ORDER BY Col2 DESC) AS RowNo,
Col1,
Col2
FROM Table
)t
WHERE t.RowNo=1
Go to Top of Page

Qualis
Posting Yak Master

145 Posts

Posted - 2008-02-13 : 15:02:41
I would go with plain old Group By (Peso's method as well). Here are the results from performance testing.

--Generate some randomish data
--500,000 Rows
Drop Table #tmp
Create Table #tmp (col1 int, col2 int)
Declare @cnt int
Set @cnt = 0

While @cnt < 100000 Begin
Insert Into #tmp Select @cnt, @cnt % 5 * 10
Insert Into #tmp Select @cnt, @cnt % 6 * 20
Insert Into #tmp Select @cnt, @cnt % 7 * 30
Insert Into #tmp Select @cnt, @cnt % 8 * 40
Insert Into #tmp Select @cnt, @cnt % 9 * 50
Set @cnt = @cnt + 1
End

--Peso
SELECT Col1, Max(Col2) FROM #tmp
GROUP BY Col1 ORDER BY Col1
/*
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 23 ms.

(100000 row(s) affected)
Table '#tmp'. Scan count 3, logical reads 1104, physical reads 0,
read-ahead reads 0, lob logical reads 0, lob physical reads 0,
lob read-ahead reads 0.
Table 'Worktable'. Scan count 0, logical reads 0, physical reads 0,
read-ahead reads 0, lob logical reads 0, lob physical reads 0,
lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 719 ms, elapsed time = 1416 ms.
*/

--visakh16
SELECT t.Col1,t.Col2
FROM
(
SELECT
ROW_NUMBER()
OVER(PARTITION BY Col1
ORDER BY Col2 DESC) AS RowNo,
Col1, Col2
FROM #tmp
) t
WHERE t.RowNo = 1
ORDER BY Col1
/*
SQL Server parse and compile time:
CPU time = 0 ms, elapsed time = 21 ms.

(100000 row(s) affected)
Table '#tmp'. Scan count 3, logical reads 1104, physical reads 0,
read-ahead reads 0, lob logical reads 0, lob physical reads 0,
lob read-ahead reads 0.

SQL Server Execution Times:
CPU time = 1545 ms, elapsed time = 2387 ms.
*/
Go to Top of Page

madhivanan
Premature Yak Congratulator

22864 Posts

Posted - 2008-02-14 : 04:26:06
I prefer using Row_number() method if I want to get top N data for each group where N>1

Madhivanan

Failing to plan is Planning to fail
Go to Top of Page
   

- Advertisement -