在三个表之间计数

时间:2014-09-03 08:26:41

标签: sql count multiple-tables

我有三张桌子

数据 服务 状态

数据表

Serno | ServiceId | Status |    Datetime
1         2           4        12/12/2014
2         1           3        08/12/2014

服务

ServiceId |  Service Name 
  1             Deployment
  2             Designing

状态

StatusId   |  Status
 1           Done
 2           Pending
 3           20%done
 4           Canceled 

我想要一个Count的Sql代码(这是关于服务的状态计数)

Designing  0  0  0  1
Deployment 0  0  1  0

我试过这个

SELECT     COUNT(Service.Status) AS Expr1, Service.ServiceName, Status.Status
FROM         Data INNER JOIN
                      Service ON Hcc_Service_Data.Hcc_Service_Category_Id = Service .ServiceId INNER JOIN
                       Status ON  Data.StatusId = Status.Status_Serno
GROUP BY Service.ServiceName, Status.Status

1 个答案:

答案 0 :(得分:0)

Select S.ServiceName, 
(CASE WHEN D.Status=1 then '1' ELSE '0' END) as S1,
(CASE WHEN D.Status=2 then '1' ELSE '0' END) as S2,
(CASE WHEN D.Status=3 then '1' ELSE '0' END) as S3,
(CASE WHEN D.Status=4 then '1' ELSE '0' END) as S4
FROM Data D, Service S where
D.serviceId = S.serviceId;