【发布时间】:2021-03-18 16:17:16
【问题描述】:
我们有针对中学生的报告周期。我正在尝试编写一个查询,该查询将创建一个简洁的小表格,显示我们每个中学年的最新报告周期。
我找到了一种方法来展示我想要的东西,但它使用 UNION 并且似乎应该有一种更有效的方法。
所以目前我重复使用了 7 次,更改了 WHERE 子句,因此 SchoolYear 更改为我们需要的每个(7 到 13):
SELECT *
FROM
(SELECT TOP 1
CycleAllocations.ReportCycle,
CycleAllocations.SchoolYear,
CycleDetails.ReportName
FROM CycleAllocations
LEFT OUTER JOIN CycleDetails
ON CycleAllocations.ReportCycle = CycleDetails.ReportCycle
WHERE SchoolYear = 7
ORDER BY intReportCycle DESC) AS CYCLE7
UNION
SELECT *
FROM
(SELECT TOP 1
CycleAllocations.ReportCycle,
CycleAllocations.SchoolYear,
CycleDetails.ReportName
FROM CycleAllocations
LEFT OUTER JOIN CycleDetails
ON CycleAllocations.ReportCycle = CycleDetails.ReportCycle
WHERE SchoolYear = 8
ORDER BY intReportCycle DESC) AS CYCLE8
UNION... etc etc
这会产生一个像这样的表格:
| ReportCycle | SchoolYear | ReportName |
|---|---|---|
| 173 | 7 | Short Report March 2021 |
| 173 | 8 | Short Report March 2021 |
| 173 | 9 | Short Report March 2021 |
| 173 | 10 | Short Report March 2021 |
| 174 | 11 | Yr11 Mock Exams Jan 2021 |
| 172 | 12 | Long Report March 2021 |
| 175 | 13 | U6 Mock Exams Jan 2021 |
有没有更好的写法?
【问题讨论】:
标签: sql sql-server ssms