限制每个 ID 的行数

2021-09-25 00:00:00 sql window-functions sql-server

我试图将每个案例的行数限制为 5 行.有些案例只有 1 或 2 行,但有些案例有 15 行或更多.

I am trying to limit the number of rows per case to only 5 rows. Some cases have only 1 or 2 rows but some have 15 or more.

这是我用来计算每个案例的行数的存储过程示例.

This is an example of a stored procedure that I am using to count the number of rows per case.

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

Here is a screenshot of what this stored procedure produces: screenshot

我尝试使用 where 子句,但它不允许我在 where 子句之后放置窗口函数.它也无法识别我的Row"别名.

I have tried to use the where clause but it will not allow me to place a window function after the where clause. It also does not recognize my "Row" alias.

是否有另一种方法来计算每个案例的数量或行数(而不是窗口函数),以便我可以使用 where 子句?或者有没有办法使用我现有的存储过程将每个案例的记录限制为 5 个?

Is there another way to count the number or rows per case (instead of a window function) so that I can use the where clause? Or is there a way to limit the records per case to 5 using my existing stored procedure?

预先感谢您的帮助.

推荐答案

您可以将语句包装在 CTE 中,因为 SQL Server 支持它.

You can wrap your statement in a CTE since SQL Server supports it.

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

相关文章