选择按主键分组的多个记录,列上具有最大值

时间:2015-02-12 10:20:10

标签: sql sql-server sql-server-2008-r2 greatest-n-per-group

我有一个包含以下结构的表(虚拟列名和数据):

+--+--+--+--+------+--------+
|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列和问题。

我需要一个声明,首先按列a,b,c和d过滤/分组,然后只选择带MAX(发行)的记录。对于此示例,结果集应如下所示:

+--+--+--+--+------+--------+
|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。

//编辑: 谢谢大家,我在另一个topic中找到了这个(非常紧凑的)解决方案:

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

2 个答案:

答案 0 :(得分:4)

试试这个:

;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

对于由a,b,c和d的唯一组合定义的组,row_number()会为您排名。

Demo

答案 1 :(得分:0)

这不仅仅是一个普通的群体吗?

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)

如果这是一个平局就会列出这两行!