具有计数和列查询的组合

时间:2014-12-04 10:05:25

标签: sql-server join having

我有一个连接表,其中包含两列的组合主键。 我想查询所有条目

columnA having count > 1

columnB = value1 and value2
到目前为止我的查询看起来像这样

select 
  columnA 
from tableA 
where columnB = 1 and 
columnA in (
         select 
           columnA 
         from tableA 
         group by columnA 
         having count(columnA) > 1) 

select 
      columnA 
    from tableA 
    where columnB = 2 and 
    columnA in (
             select 
               columnA 
             from tableA 
             group by columnA 
             having count(columnA) > 1) 

我该如何查询

...columnB = 1 and columnB = 2 and columnA in (select ....

1 个答案:

答案 0 :(得分:2)

select columnA 
from tableA 
where columnB in (1,2)
group by columnA 
having count(distinct columnB) = 2

自动1填充2columnB两个值count(columnA) > 1

如果您希望 columnB条件(columnB有2个值) columnA条件,那么

select columnA 
from tableA 
group by columnA 
having count(*) > 1
or count(distinct columnB) = 2

columnB必须为12

select columnA 
from tableA 
group by columnA 
having count(*) > 1
or 
( 
   sum(case when columnB = 1 then 1 else 0 end) > 0 and
   sum(case when columnB = 2 then 1 else 0 end) > 0
)