返回零与A组数查询BY

问题描述:

在我修表,我想计算每种状态的汽车(1,2,3和4):返回零与A组数查询BY

Status 1: 5 
Status 2: 0 
Status 3: 6 
Status 4: 3 

,因为它表明,在状态没有汽车2,所以,我做了相同的查询4次与“WHEN状态=='n'在每个状态计数,并且工作正常。

现在我想只在一个查询中,但在我的查询:

select status,count(car_id)from repairs GROUP BY status。

告诉我这一点:

Status 1: 5 
Status 3: 6 
Status 4: 3 
+0

是'status'和'repairs'存储在不同的表? –

+0

@DarshanMehta我只有一个包含car_id和包含int数字1-2-3或4的状态行的修复表。 –

+0

您确定您的表中有状态2。 –

你将需要一个源,可能是一个表,其中包含要在报表中显示的每个状态。一种方式是“日历表”方法,您可以将包含每种状态的表格加入到当前查询中,例如

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 
+0

鉴于这个问题也被标记为'PHP',我认为这是一个不太合适的解决方案 – Strawberry

+1

@Strawberry我不同意你。没有必要的数据来回答业务查询与应用程序语言无关。除非你打算从PHP处理这个问题,我认为这不是一个好主意。 –

试试这个:

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);