选择进入查询,添加带有不同子句的第二个计数列

时间:2014-02-24 11:51:01

标签: sql sql-server sql-server-2012

我有如下查询,可以正常使用:

select id_matched
     , count(*) s_count
  into STEVEN_1c 
  from batch 
 where match = 200 
 group by 
       id_matched 

现在我想在此查询中添加第二个计数列,这是一个稍微更具体的查询,它还会检查另一列,即添加名为“count_unique”的列,其中“unique”列为“1”。

类似

select id_matched
     , count(*) s_count
     , count(* + and unique=1) count_unique
  into STEVEN_1c 
  from batch 
 where match = 200 
 group by 
       id_matched 

只是不确定添加第二个比第一个更具体的计数列的语法是什么?

2 个答案:

答案 0 :(得分:0)

试试这个:

select id_matched
     , count(*) s_count
     , sum(case when unique = 1 then 1 else 0 end) count_unique
  into STEVEN_1c 
  from batch 
 where match = 200 
 group by 
       id_matched 

答案 1 :(得分:0)

您可以在计数函数中编写一个案例条件,如下所示:

select id_matched
, count(*) s_count
, count(case [unique] when 1 then 1 else null end) as count_unique
into STEVEN_1c 
from batch 
where match = 200 
group by 
id_matched