单个sql中有多个count * sql

时间:2015-01-29 14:08:14

标签: mysql sql-server

我想将这些sql语句用作单个语句,这将导致4columns具有不同的count和company_id。

select company_id,count(*) as det from feedbacks a join( select id,company_id from users  ) b on a.user_id = b.id where healthi_rating < 7 group by company_id
select company_id,count(*) as neu from feedbacks a join( select id,company_id from users  ) b on a.user_id = b.id where healthi_rating <9 && healthi_rating >=7 group by company_id
select company_id,count(*) as pro from feedbacks a join( select id,company_id from users  ) b on a.user_id = b.id where healthi_rating >=9 group by company_id

有人可以让我知道如何做到这一点。

1 个答案:

答案 0 :(得分:4)

对于MySQL做

select company_id,
       sum(healthi_rating < 7) as det,
       sum(healthi_rating between 7 and 8) as neu,
       sum(healthi_rating >= 9) as pro
from feedbacks a 
join( select id, company_id from users ) b on a.user_id = b.id 
group by company_id

并使用ANSI SQL Standard且没有users

的子查询
select b.company_id,
       sum(case when healthi_rating < 7 then 1 else 0 end) as det,
       sum(case when healthi_rating between 7 and 8 then 1 else 0 end) as neu,
       sum(case when healthi_rating >=9 then 1 else 0 end) as pro
from feedbacks a 
join users b on a.user_id = b.id 
group by b.company_id