分组依据的SQL查询作为内部查询

时间:2020-03-05 11:36:16

标签: sql group-by

我有一个如下表

TestDetails

Submitted_on                      Subject    Submitted_By
3/4/2020 7:45:26 PM               English       Shyam
3/4/2020 9:45:26 PM               English       Rahul
3/5/2020 9:45:26 PM               Arabic        Rahul
3/4/2020 8:45:26 PM               French        Yash
3/4/2020 7:45:26 PM               Spanish       John
3/4/2020 6:45:26 PM               Spanish       John

我想从上表中为每个主题选择最新提交的内容。 输出应为:

 Submitted_on                     Subject    Submitted_By
3/4/2020 9:45:26 PM               English       Rahul
3/5/2020 9:45:26 PM               Arabic        Rahul
3/4/2020 8:45:26 PM               French        Yash
3/4/2020 7:45:26 PM               Spanish       John

我尝试过如下 但是将输出作为

 Submitted_on                    Subject    Submitted_By
3/4/2020 7:45:26 PM               English       Shyam
3/4/2020 9:45:26 PM               English       Rahul
3/5/2020 9:45:26 PM               Arabic        Rahul
3/4/2020 8:45:26 PM               French        Yash
3/4/2020 7:45:26 PM               Spanish       John


SELECT MAX(Submitted_on),Subject,Submitted_By FROM TestDetails GROUP BY Subject,Submitted_By

2 个答案:

答案 0 :(得分:0)

使用过滤。这是一种方法:

select td.*
from testdetails td
where td.Submitted_on = (select max(td2.Submitted_on)
                         from testdetails td2
                         where td2.subject = td.subject
                        );

要获得更大数据集的性能,您需要在testdetails(subject, submitted_on)上建立索引。

答案 1 :(得分:0)

找到以下查询

;WITH CTE AS
(
    SELECT ROW_NUMBER() OVER (PARTITION BY subject ORDER BY subject DESC) duplicates, * 
    FROM TestDetails
)
SELECT submitted_on, subject, submitted_by FROM CTE WHERE duplicates = 1