我使用行计数返回值匹配1或2.我需要保持所有值等于2.但是,根据我正在尝试的列名,行数为1的某些值是相同的过滤。我正在寻找的是一种方法来保持计数为2的行,但只有当行数为2时才排除计数为1的行。在下面的示例中,我返回相同的销售订单ID为528886但希望排除该行,因为它有第2行。
查询:
select * from (
select *, ROW_NUMBER() over (partition by SalesOrderPostedID
Order By SalesOrderPostedID) as RowNumber
from cte5) c
Where SalesOrderPostedID=528886
and c.RowNumber=1
Union all
select * from (
select *, ROW_NUMBER() over (partition by SalesOrderPostedID
Order By SalesOrderPostedID) as RowNumber
from cte5) c
Where SalesOrderPostedID=528886
and c.RowNumber=2
我附上了结果。
Gorgon提供的解决方案略有修改。下面的查询返回所有具有一个或两个计数的行或任何只有一个计数的行。
选择c。* 从(选择cte5。, row_number()over(按SalesOrderPostedID分区) 按SalesOrderPostedID排序 )作为RowNumber, 将()计数(由SalesOrderPostedID分区)作为cnt计数 来自cte5 ) C 其中(RowNumber = 2或 cnt = 1);
答案 0 :(得分:1)
为什么你不这样做?
select c.*
from (select c.*,
row_number() over (partition by SalesOrderPostedID
Order By SalesOrderPostedID
) as RowNumber
from cte5
) c
where SalesOrderPostedID = 528886 and c.RowNumber <= 2;
如果您只想要成对行,请使用:
select c.*
from (select c.*,
row_number() over (partition by SalesOrderPostedID
Order By SalesOrderPostedID
) as RowNumber,
count(*) over (partition by SalesOrderPostedID) as cnt
from cte5
) c
where SalesOrderPostedID = 528886 and RowNumber <= 2 and
cnt >= 2;