限制每个 ID 的行数

Limit the number of rows per ID(限制每个 ID 的行数)
本文介绍了限制每个 ID 的行数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我试图将每个案例的行数限制为 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

这篇关于限制每个 ID 的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

Union in SQL while creating XML file(创建 XML 文件时在 SQL 中联合)
strange behavior of SQL Server when sum nodes#39;s values in XML(对 XML 中的节点值求和时 SQL Server 的奇怪行为)
How to update a SQL table column with XML data(如何使用 XML 数据更新 SQL 表列)
How To Save XML Query Results to a File(如何将 XML 查询结果保存到文件)
Extracting XML sub-tags from a clob in Oracle via SQL(通过 SQL 从 Oracle 中的 clob 中提取 XML 子标签)
installed Xampp on Windows 7 32-bit. Errors when starting(在 Windows 7 32 位上安装 Xampp.启动时的错误)