我有一个表,我想查询返回结果,其中位列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行。
答案 0 :(得分:2)
您可以将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
答案 1 :(得分:0)
如果您想要所有行(unaggregated),那么您可以使用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的方法是正确的。