在我的维修表中,我想要每个状态(1,2,3和4)计数汽车:
q
如图所示,状态2上没有汽车,因此,我使用“WHEN status =='n'进行相同的查询4次,以计算每个状态,并且工作正常。
现在我只想在一个查询中,但在我的查询中:
从
Status 1: 5 Status 2: 0 Status 3: 6 Status 4: 3
GROUP BY状态选择状态,计数(car_id)。
告诉我这个:
repairs
答案 0 :(得分:1)
您需要一个源,可能是一个表,其中包含您希望在报告中显示的每个状态。一种方法是"日历表"您加入包含当前查询的每个状态的表的方法,例如
SELECT
t1.status,
COALESCE(t2.car_cnt, 0) AS car_cnt
FROM
(
SELECT 1 AS status UNION ALL -- replace this ad-hoc subquery with
SELECT 2 UNION ALL -- an actual "calendar" table of statuses
SELECT 3 UNION ALL -- or if you already have such a table, use that
SELECT 4
) t1
LEFT JOIN
(
SELECT status, COUNT(car_id) AS car_cnt
FROM repairs
GROUP BY car_id
) t2
ON t1.status = t2.status
答案 1 :(得分:0)
试试这个:
SELECT status, count(car_id)
FROM repairs GROUP BY car_id
UNION
SELECT status, 0
FROM repairs WHERE status NOT IN
(SELECT status FROM repairs GROUP BY car_id);