我有以下两个表:
Table A:
--------
Id Service
101 S1
101 S1
101 S2
101 S2
102 S4
Table B:
--------
Service Status
S1 Active
S1 Active
S2 Inactive
S2 Inactive
S4 Cancelled
Result Required:
----------------
Id Service Count Status
101 S1 2 Active
101 S2 2 Inactive
102 S4 1 Cancelled
我们如何编写一个sql-query来根据需要的结果从这两个表中获取数据?
非常感谢你的帮助!
编辑:
有没有办法可以填充不同的'计数列'该表同时使用相同的SQL查询。例如,如果需要以下列形式的结果:
Id Service Active_Count Inactive_Count Cancelled_Count
---------------------------------------------------------------------
101 S1 2 0 2
101 S1 0 2 0
102 S4 0 0 1
答案 0 :(得分:2)
select id, A.service, count(1), status
from A, B
where A.service = B.service
group by id, A.service, status
答案 1 :(得分:0)
试试这个:
select id, A.service, count(1), status
from A inner join B on A.service = B.service
group by id, A.service, status