如何计算最近 7 天的报告运行次数?今年迄今为止?整天?

How to count number of report runs last 7 days? Year to date? All time?

我正在尝试创建类似于下面 table 的 SSRS 报告:

Report Earliest Run Recent Run Runs Last 7 days Runs YTD Runs All Time
Report 1 3/3/19 1:30 7/8/22 2:45 8 86 233

我知道如何单独查询最后 3 列,但是否可以使用 1 个查询获取所有 3 列?我尝试了下面的查询来展示我的思路,但它没有按预期工作。

SELECT Report
  ,Min(TimeStart) AS EarliestRun
  ,Max(TimeStart) AS RecentRun
  ,CASE WHEN TimeStart BETWEEN GETDATE()-7 AND GETDATE() THEN COUNT(Report) END AS RunsLast7Days
FROM ReportHistory
WHERE TimeStart BETWEEN '1/1/2019 00:00' AND GETDATE()
GROUP BY Report

是 - 使用条件聚合。根本不要过滤查询,因为您需要一个“所有时间”值。相反,对感兴趣的时间段使用带有条件表达式的总和。

select ... 
sum(case when TimeStart >= dateadd(day, -7, getdate()) then 1 else 0 end) as [Runs Last 7 days], 
sum(case when TimeStart >= datefromparts(year(getdate()), 1, 1) then 1 else 0 end) as [Runs YTD], 
... 
from dbo.ReportHistory
order by ...;

我打算建议使用 CROSS APPLY,但 SMor 用更少的代码完成了它

CREATE TABLE #Reports (
    ReportId INT NOT NULL,
    ReportName VARCHAR(20) NOT NULL
);

INSERT INTO #Reports(ReportId, ReportName)
VALUES(1,  'Report 1');

CREATE TABLE #ReportRun (
    ReportId INT,
    RunDateTime DATETIME2(2)
);

INSERT INTO #ReportRun(ReportId, RunDateTime)
VALUES
(1, '20220508 10:00:00'),
(1, '20220502 10:00:00'),
(1, '20220101 10:00:00'),
(1, '20210501 10:00:00'),
(1, '20210209 10:00:00'),
(1, '20200509 10:00:00'),
(1, '20190509 10:00:00');

GO

-- SELECT * FROM #Reports
-- SELECT * FROM #ReportRun

SELECT R.ReportName, B.RunLast7Days, C.RunYearToDate, D.RunAllTime
FROM #Reports AS R
CROSS APPLY (
    SELECT TOP 1 RunDateTime
    FROM #ReportRun
    WHERE ReportId = R.ReportId
    ORDER BY RunDateTime DESC
) AS ER
CROSS APPLY (
    SELECT COUNT(*) AS RunLast7Days
    FROM #ReportRun
    WHERE ReportId = R.ReportId
    AND RunDateTime >= DATEADD(day, -7, CONVERT(date, GETDATE())) -- best to set it to the start of the day
    GROUP BY ReportId
) AS B
CROSS APPLY (
    SELECT COUNT(*) AS RunYearToDate
    FROM #ReportRun
    WHERE ReportId = R.ReportId
    AND RunDateTime >= DATEADD(yy, DATEDIFF(yy, 0, GETDATE()), 0)
    GROUP BY ReportId
) AS C
CROSS APPLY (
    SELECT COUNT(*) AS RunAllTime
    FROM #ReportRun
    WHERE ReportId = R.ReportId
    GROUP BY ReportId
) AS D