现有一个表A,里面有字段companyid,type(type=1,2,3),status(status=维修,停用,使用)
现在要统计成如下格式
-----------------------------------------------------------------------------------
公司 | type=1 | type = 2 | type =3
|总数|维修数|停用数|使用数| 总数|维修数|停用数|使用数 |总数|维修数停用数|使用数
----------------------------------------------------------------------------------
如何使用sql语句?
select companyid ,
sum(case when type=1 then 1 else 0 end) [1_总数],
sum(case when type=1 and status='维修' then 1 else 0 end) [1_维修数],
sum(case when type=1 and status='停用' then 1 else 0 end) [1_停用数],
sum(case when type=1 and status='使用' then 1 else 0 end) [1_使用数],
sum(case when type=2 then 1 else 0 end) [2_总数],
sum(case when type=2 and status='维修' then 1 else 0 end) [2_维修数],
sum(case when type=2 and status='停用' then 1 else 0 end) [2_停用数],
sum(case when type=2 and status='使用' then 1 else 0 end) [2_使用数],
sum(case when type=3 then 1 else 0 end) [3_总数],
sum(case when type=3 and status='维修' then 1 else 0 end) [3_维修数],
sum(case when type=3 and status='停用' then 1 else 0 end) [3_停用数],
sum(case when type=3 and status='使用' then 1 else 0 end) [3_使用数]
from a
group by companyid