SQL 服务器:select 个具有最新更新报告的组
SQL Server : select groups with latest updated reports
我需要一个 select 查询来根据其中更新的最新报告列出报告组。
例如,此查询列出了报告组及其报告的最大创建日期:
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
我想这就是您要找的。更改为基于连接的选择并按内部(最大)创建日期排序。
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;
我需要一个 select 查询来根据其中更新的最新报告列出报告组。
例如,此查询列出了报告组及其报告的最大创建日期:
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
我想这就是您要找的。更改为基于连接的选择并按内部(最大)创建日期排序。
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;