我试图将每个案例的行数限制为仅5行。有些情况只有1或2行,但有些只有15或更多。
这是我用来计算每个案例的行数的存储过程的示例。
SELECT ROW_NUMBER() OVER(partition by rce.reportruncaseid ORDER BY rce.Reportruncaseid) AS Row, rce.ReportRunCaseId AS CaseId, YEAR(rce.EcoDate) AS EcoYear
FROM PhdRpt.ReportCaseList AS rcl INNER JOIN
PhdRpt.RptCaseEco AS rce ON rce.ReportId = rcl.ReportId AND rce.ReportRunCaseId = rcl.ReportRunCaseId
GROUP BY rce.ReportId, rce.ReportRunCaseId, YEAR(rce.EcoDate)
Order by rce.ReportRunCaseId, YEAR(rce.EcoDate)
以下是此存储过程生成的屏幕截图:screenshot
我试过使用where子句但是它不允许我在where子句之后放置一个窗口函数。它也无法识别我的“行”别名。
有没有其他方法来计算每个案例的数量或行数(而不是窗口函数),以便我可以使用where子句?或者有没有办法使用我现有的存储过程将每个案例的记录限制为5?
提前感谢您的帮助。
答案 0 :(得分:1)
您可以将自己的陈述用CTE
包裹,因为SQL Server
支持它。
WITH records
AS
(
SELECT ROW_NUMBER() OVER(PARTITION BY rce.reportruncaseid
ORDER BY rce.Reportruncaseid) AS Row,
rce.ReportRunCaseId AS CaseId,
YEAR(rce.EcoDate) AS EcoYear
FROM PhdRpt.ReportCaseList AS rcl
INNER JOIN PhdRpt.RptCaseEco AS rce
ON rce.ReportId = rcl.ReportId
AND rce.ReportRunCaseId = rcl.ReportRunCaseId
GROUP BY rce.ReportId, rce.ReportRunCaseId, YEAR(rce.EcoDate)
)
SELECT CaseId, EcoYear
FROM records
WHERE row <= 10
ORDER BY CaseId, EcoYear