SQL Server:选择包含最新更新报告的组

时间:2015-03-08 07:03:09

标签: sql sql-server tsql

我需要一个选择查询来根据其中更新的最新报告列出ReportGroup。

例如,

此查询列出了具有最大创建日期的报告组:

SELECT TOP 100 PERCENT rg.ReportGroupID
FROM Report.ReportGroups as rg
INNER JOIN Report.Reports as r ON rg.ReportGroupID = r.ReportGroupID
GROUP BY rg.ReportGroupID
ORDER BY MAX(CreateDate) DESC

输出:

20|2015-02-28
8 |2015-02-17
1 |2015-02-10
36|2015-01-11
25|2014-12-20
18|2014-12-16

现在,我需要所有ReportGroup列:

SELECT * 
FROM Report.ReportGroups 
WHERE ReportGroupID IN (
    SELECT TOP 100 PERCENT rg.ReportGroupID
    FROM Report.ReportGroups as rg
    INNER JOIN Report.Reports as r ON rg.ReportGroupID = r.ReportGroupID
    GROUP BY rg.ReportGroupID
    ORDER BY MAX(CreateDate) DESC
)

输出:

1 |Group 1
8 |Group 8
18|Group 18
20|Group 20
25|Group 25
36|Group 36

但此查询的结果与上一个查询的排序方式不同。

感谢。

2 个答案:

答案 0 :(得分:1)

您可以使用外部申请执行此操作:

SELECT
  rg.*
FROM 
  Report.ReportGroups as rg
  outer apply (
    select top 1 r.CreateDate 
    from Report.Reports as r
    where rg.ReportGroupID = r.ReportGroupID
    order by r.CreateDate DESC
  ) r
ORDER BY 
    r.CreateDate DESC

答案 1 :(得分:1)

我认为这是你正在寻找的东西。已更改为基于联接的选择,并按内部(最大)创建的顺序排序。

SELECT rg1.* 
FROM Report.ReportGroups rg1
JOIN (
    SELECT TOP 100 PERCENT rg.ReportGroupID, MAX(CreateDate) createdate
    FROM Report.ReportGroups as rg
    INNER JOIN Report.Reports as r ON rg.ReportGroupID = r.ReportGroupID
    GROUP BY rg.ReportGroupID
    ORDER BY MAX(CreateDate) DESC
) trg ON rg1.ReportGroupID = trg.ReportGroupID
ORDER BY trg.createdate;