繁体   English   中英

SQL Server:选择具有最新更新报告的组

[英]SQL Server : select groups with latest updated reports

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

例如,此查询列出报告组的最大创建日期:

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

但是此查询的结果不像上一个查询那样排序。

谢谢。

您可以使用外部应用来执行此操作:

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

我认为这就是您要寻找的。 更改为基于联接的选择,并按内部(最大)createdate进行排序。

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;

暂无
暂无

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

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