我正在使用 SQL Server 2008-R2 和 Transact SQL。
我有一个状态报告,它从多个表/视图返回数据并使用 UNION 将行“连接”在一起。
SQL 脚本的摘录是
SELECT
NR.FormStatus AS [Item],
(SELECT COUNT(PerinatalReportID) FROM NotificationDatesForReport
WHERE FormStatus = NR.FormStatus AND NotificationDate BETWEEN dbo.DateNoTime(GetDate()) AND dbo.DateNoTime(GetDate() + 1)) AS [Today],
(SELECT COUNT(PerinatalReportID) FROM NotificationDatesForReport WHERE FormStatus = NR.FormStatus) AS [Total]
FROM
NotificationDatesForReport AS NR
GROUP BY
NR.FormStatus, NR.DisplayOrder
UNION ALL
SELECT
'Distinct password requests',
(SELECT COUNT(DISTINCT ToEMail) FROM PasswordRequests
WHERE DateProcessed BETWEEN dbo.DateNoTime(GetDate()) AND dbo.DateNoTime(GetDate() + 1)) AS [Today],
(SELECT COUNT(DISTINCT ToEMail) FROM PasswordRequests) AS [Total]
这可以按预期工作,但是,带有子句的脚本第一部分中的项目顺序GROUP BY
以随机顺序出现。我想做的是只对脚本的那一部分进行排序,但我找不到方法来做,因为SORT
BY 子句必须在最后一个 UNION 之后。
欢迎所有建议。