繁体   English   中英

如何按至少两行具有不同列值的位置分组

[英]How to group by where at least two rows have differing column values

我有一个表,我想查询该表以返回结果,其中位列IsValid对于至少两行具有相反的值。

TableA
    UniqueId
    Column1
    Column2
    Column3
    IsValid (bit values 0 and 1)

按列1,2,3进行分组我需要返回至少有两行具有IsValid 0和1的整个行。

Val1 | Val1 | Val1 | 0
Val1 | Val1 | Val1 | 1

Val2 | Val2 | Val2 | 0
Val2 | Val2 | Val2 | 1
Val2 | Val2 | Val2 | 1

Val3 | Val3 | Val3 | 0
Val3 | Val3 | Val3 | 0

将返回所有行Val1和Val2,而不会返回Val3行。

您可以将group by与一起having

select column1,column2,column3
from tableA
group by column1,column2,column3
having count(case when isvalid=1 then 1 end) >= 1
and count(case when isvalid=0 then 1 end) >= 1

要么

select column1,column2,column3
from tableA
group by column1,column2,column3
having min(cast(isvalid as int)) = 0 and max(cast(isvalid as int))= 1

如果您希望所有 (未聚合),则可以使用exist exists

select a.*
from tableA a
where exists (select 1
              from tableA a2
              where a2.column1 = a.column1 and
                    a2.column2 = a.column2 and
                    a2.column3 = a.column3 and
                    isvalid = 0
             ) and
      exists (select 1
              from tableA a2
              where a2.column1 = a.column1 and
                    a2.column2 = a.column2 and
                    a2.column3 = a.column3 and
                    isvalid = 1
             );

如果您想要汇总值,那么@vkp的方法是正确的。

暂无
暂无

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

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