2011-09-22 104 views
3

在SQL Server中,我有一個整數,日期時間和字符串的列表。例如,如何在SQL中選擇每個列的最大值?

number datetime    string 
6  2011-09-22 12:34:56 nameOne 
6  2011-09-22 1:23:45 nameOne 
6  2011-09-22 2:34:56 nameOne 
5  2011-09-22 3:45:01 nameOne 
5  2011-09-22 4:56:01 nameOne 
5  2011-09-22 5:01:23 nameOne 
7  2011-09-21 12:34:56 nameTwo 
7  2011-09-21 1:23:45 nameTwo 
7  2011-09-21 2:34:56 nameTwo 
4  2011-09-21 3:45:01 nameTwo 
4  2011-09-21 4:56:01 nameTwo 
4  2011-09-21 5:01:23 nameTwo 

我想寫一條SQL語句,它只輸出那些對每個字符串來說最大數量的行。在這個例子中,

number datetime    string 
6  2011-09-22 12:34:56 nameOne 
6  2011-09-22 1:23:45 nameOne 
6  2011-09-22 2:34:56 nameOne 
7  2011-09-21 12:34:56 nameTwo 
7  2011-09-21 1:23:45 nameTwo 
7  2011-09-21 2:34:56 nameTwo 

我知道我可以循環遍歷字符串列中的每個字符串,然後得到最大的爲字符串,然後選擇最大匹配的行。例如,

declare @max int 
declare my_cursor cursor fast_forward for 
    select distinct string 
    from table 
open my_cursor 
fetch next from my_cursor into @string 
while @@fetch_status = 0 
begin 
    set @max = (select max(number) from table where string = @string) 
    select * from table where number = @max 
    fetch next from my_cursor into @string 
end 
close my_cursor 
deallocate my_cursor 

然而,我想知道如果有一種方法來完成此任務WITHOUT使用循環(例如,通過使用聚合函數和分組)。

回答

1
;WITH T as 
(
SELECT *, 
     RANK() OVER (PARTITION BY string ORDER BY number DESC) RN 
FROM YourTable 
) 
SELECT number, 
     datetime, 
     string 
FROM T 
WHERE RN=1; 
0
WITH maxes AS (
    SELECT string, MAX(number) AS max_number 
    FROM tbl 
    GROUP BY string 
) 
SELECT tbl.* 
FROM tbl 
INNER JOIN maxes 
    ON maxes.string = tbl.string AND maxes.max_number = tbl.number 
相關問題