按多种条件计算

时间:2015-06-09 00:49:12

标签: sql sql-server tsql

这是我的数据,我需要以最快的方式获得结果。

enter image description here

3 个答案:

答案 0 :(得分:5)

标准条件聚合:

select city,
       sum(case when active = 'true' then 1 else 0 end) active,
       sum(case when blacklist = 'true' then 1 else 0 end) blacklist,
       sum(case when license = 'true' then 1 else 0 end) license,
       sum(case when married = 'true' then 1 else 0 end) married
from TableName
group by city

答案 1 :(得分:3)

这给出了你期待的输出

 declare @t table (code int,name varchar(10),Active varchar(5),Black varchar(5),License varchar(5),married varchar(5),city int)
    insert into @t (code,name,Active,Black,License,married,city)values (1,'john','true','false','true','true',1001),
    (2,'jack','true','true','true','fale',1002),
    (3,'sara','false','false','false','true',1001),
    (4,'shiela','true','false','false','false',1002)
    ;with cte as (
    select distinct city,
    CASE WHEN Active = 'true' then COUNT(ACTIVE)else NULL end ACTIVE,
    CASE WHEN Black = 'true' then COUNT(Black)else NULL end BLACK,
    CASE WHEN License = 'true' then COUNT(License)else NULL end License,
    CASE WHEN married = 'true' then COUNT(married)else NULL  end married from @t
    group by city,active,Black,License,married)
select DISTINCT city,COUNT(ACTIVE)[ACTIVE(*)],COUNT(Black)[Black(*)],COUNT(License)[License(*)],COUNT(married)[married(*)]  from cte 
GROUP BY CITY

答案 2 :(得分:2)

你走了。我使用的事实是,count函数不计算空值。

Select City, 
COUNT(NULLIF(Active,'FALSE')),
COUNT(NULLIF(Blacklist,'FALSE')),
COUNT(NULLIF(License,'FALSE')),
COUNT(NULLIF(Married,'FALSE'))
From TableName
Group by City