[英]Select multiple records grouped by primary key with max value on a column
我有一個具有以下結構的表(虛擬列名和數據):
+--+--+--+--+------+--------+
|a |b |c |d |issue |content |
+--+--+--+--+------+--------+
|a |b |c |d |1 | |
|a |b |c |d |2 | |
|a |b |c |d |3 | |
|d |e |f |g |1 | |
|d |e |f |g |2 | |
|e |f |g |h |1 | |
+--+--+--+--+------+--------+
我的主鍵包含a,b,c,d和issue列。
我需要一條語句,該語句首先按a,b,c和d列過濾/分組,然后僅選擇具有MAX(issue)的記錄。 對於此示例,結果集應如下所示:
+--+--+--+--+------+--------+
|a |b |c |d |issue |content |
+--+--+--+--+------+--------+
|a |b |c |d |3 | |
|d |e |f |g |2 | |
|e |f |g |h |1 | |
+--+--+--+--+------+--------+
我知道如何對一條特定記錄執行此操作,但是我無法弄清楚如何對所有記錄執行此操作:
SELECT TOP 1 * FROM Test_Max_N_Per_Group
WHERE a = 'a' AND b = 'b' AND c = 'c' AND d = 'd'
ORDER BY issue DESC
我正在使用Microsoft SQL Server 2008 R2。
//編輯:謝謝大家,我在另一個主題中找到了這個(非常緊湊的)解決方案:
SELECT t1.* FROM Test_Max_N_Per_Group t1
LEFT JOIN Test_Max_N_Per_Group t2
ON t1.a = t2.a AND t1.b = t2.b AND t1.c = t2.c AND t1.d = t2.d AND
t1.issue < t2.issue
WHERE t2.issue IS NULL
嘗試這個:
;with cte as
(select a,b,c,d, issue, row_number() over (partition by a,b,c,d order by issue desc) maxval, content
from yourtable)
select a,b,c,d,issue,content
from cte
where maxval = 1
該row_number()在由a,b,c和d的唯一組合定義的組上為您排名。
這不是一個簡單的團體嗎?
SELECT a, b, c, d, MAX(issue)
FROM tablename
GROUP BY a, b, c, d
如果還需要內容:
SELECT a, b, c, d, issue, contents
FROM tablename t1
WHERE issue = (select max(issue) from tablename t2
where t1.a = t2.a
and t1.b = t2.b
and t1.c = t2.c
and t1.d = t2.d)
如果是平局,將列出兩行!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.