限制每个 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 的行数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Execute complex raw SQL query in EF6(在EF6中执行复杂的原始SQL查询)
Hibernate reactive No Vert.x context active in aws rds(AWS RDS中的休眠反应性非Vert.x上下文处于活动状态)
Bulk insert with mysql2 and NodeJs throws 500(使用mysql2和NodeJS的大容量插入抛出500)
Flask + PyMySQL giving error no attribute #39;settimeout#39;(FlASK+PyMySQL给出错误,没有属性#39;setTimeout#39;)
auto_increment column for a group of rows?(一组行的AUTO_INCREMENT列?)
Sort by ID DESC(按ID代码排序)