简体   繁体   English

如何根据每组的条件过滤记录

[英]How to filter records based on a criteria per group

In SQL how can I express this question: For all groups, return all records in a group that match the result of a condition specific to the group.在 SQL 中,我如何表达这个问题:对于所有组,返回组中与特定于该组的条件的结果匹配的所有记录。

For example:例如:

Book: (Id, Name, AuthorName, PublishDate)

Return all records in Book table that if the books are grouped by the AuthorName , they are the fifth or later books of that specific author.返回Book表中的所有记录,如果这些书籍按AuthorName分组,则它们是该特定作者的第五本书或以后的书籍。

I'm using MS SQL Server 2016.我正在使用 MS SQL Server 2016。

The solution to this is basically the same as Get top 1 row of each group , however, instead of = 1 you want >=5 :对此的解决方案与Get top 1 row of each group基本相同,但是,您想要的不是= 1 >=5

WITH CTE AS(
    SELECT {Columns}
           ROW_NUMBER() OVER (PARTITION BY Author ORDER By PublishDate) AS RN
    FROM dbo.YourTable)
SELECT {Columns
FROM CTE
WHERE RN >= 5;

You can also use a correlated subquery for this:您还可以为此使用相关子查询:

select t.*
from t
where t.publishdate >= (select t2.publishdate
                        from t t2
                        where t2.author = t.author 
                        order by t2.publishdate asc
                        offset 4 fetch first 1 row only
                       );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM