我具有以下表格结构
leads
-id
-fname
-lname
subcontractors
-id
-leads_id
-fname
-lname
-status
铅可以有许多subcontractors
。 subcontractors.status
告知分包商是处于活动状态还是已暂停
问题是我该如何选择带有计数列的销售线索,以告诉他们有多少个活动和暂停的子图标?
我现在有这个:
SELECT
l.id,
l.fname,
l.lname,
s.status
FROM leads l
INNER JOIN subcontractors s
ON l.id = s.leads_id
GROUP BY l.id ORDER BY l.id DESC;
我的目标是拥有这样的东西
id | fname | lname | active_subcon_count | suspended_subcon_count
答案 0 :(得分:4)
您可以尝试将条件汇总函数COUNT
与CASE WHEN
一起使用
SELECT
l.id,
l.fname,
l.lname,
COUNT(CASE WHEN s.status = 'active' THEN 1 END) ,
COUNT(CASE WHEN s.status = 'suspended' THEN 1 END)
from leads l
INNER JOIN subcontractors s
ON l.id = s.leads_id
GROUP BY l.id , l.fname, l.lname
ORDER BY l.id DESC;
或者mysql可以这样做SUM
。
SELECT
l.id,
l.fname,
l.lname,
SUM(s.status = 'active') active_subcon_count ,
SUM(s.status = 'suspended') suspended_subcon_count
from leads l
INNER JOIN subcontractors s
ON l.id = s.leads_id
GROUP BY l.id , l.fname, l.lname
ORDER BY l.id DESC;