简体   繁体   English

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

[英]Select multiple records grouped by primary key with max value on a column

I have a table with the following structure (dummy column names and data): 我有一个具有以下结构的表(虚拟列名和数据):

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

My primary key contains columns a, b, c, d and issue. 我的主键包含a,b,c,d和issue列。

I need a statement that first filters / groups by columns a, b, c and d and then only selects the record with MAX(issue). 我需要一条语句,该语句首先按a,b,c和d列过滤/分组,然后仅选择具有MAX(issue)的记录。 For this example the result set should look like this: 对于此示例,结果集应如下所示:

+--+--+--+--+------+--------+
|a |b |c |d |issue |content |
+--+--+--+--+------+--------+
|a |b |c |d |3     |        |
|d |e |f |g |2     |        |
|e |f |g |h |1     |        |
+--+--+--+--+------+--------+

I know how I would do this for one specific record, but I cannot figure out how to do it for all the records: 我知道如何对一条特定记录执行此操作,但是我无法弄清楚如何对所有记录执行此操作:

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

I am using Microsoft SQL Server 2008 R2. 我正在使用Microsoft SQL Server 2008 R2。

// Edit: Thank you guys, I found this (very compact) solution in another 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

Try this: 尝试这个:

;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

That row_number() does your ranking for you over groups defined by unique combinations of a,b,c and d. 该row_number()在由a,b,c和d的唯一组合定义的组上为您排名。

Demo 演示

Isn't this just a plain group by? 这不是一个简单的团体吗?

SELECT a, b, c, d, MAX(issue)
FROM tablename
GROUP BY a, b, c, d

If contents also is required: 如果还需要内容:

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)

Will list both rows if it's a tie! 如果是平局,将列出两行!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM