我需要使用COUNT()函数选择表中不存在的数据为零,如何使用Sql来选择

时间:2019-05-25 13:40:39

标签: mysql sql

例如:

SELECT COUNT(num) AS number, Status
FROM base
WHERE Status in ('P', 'J', 'K') 
GROUP BY Status;

注意:“状态”列中不存在J和K,但我需要将数字显示为零

结果应为:

number | Status
---------------
1500   | P
0      | J
0      | K

4 个答案:

答案 0 :(得分:5)

您可以使用派生表和LEFT JOIN

SELECT count(base.num) AS number, s.Status 
FROM (SELECT 'P' AS Status UNION ALL SELECT 'J' UNION ALL SELECT 'K') s
LEFT JOIN base ON s.status = base.Status
group by s.Status;

答案 1 :(得分:3)

如果您不介意将结果作为而不是行,那么我们可以在此处尝试使用条件聚合:

SELECT
    COUNT(CASE WHEN Status = 'P' THEN 1 END) AS p_cnt,
    COUNT(CASE WHEN Status = 'J' THEN 1 END) AS j_cnt,
    COUNT(CASE WHEN Status = 'K' THEN 1 END) AS k_cnt
FROM base;

@Lukasz建议的派生表想法是一个好主意,无论如何您都应该为Stati建立一个单独的表。

答案 2 :(得分:1)

您可以使用UNPIVOT作为

,轻松UNION ALL数据
SELECT COUNT(num) AS number, coalesce(Status,'P') AS Status FROM base WHERE Status = 'P' 
UNION ALL
SELECT COUNT(num)          , coalesce(Status,'J')           FROM base WHERE Status = 'J' 
UNION ALL
SELECT COUNT(num)          , coalesce(Status,'K')           FROM base WHERE Status = 'K';

如果将来插入了某些行,它们的状态为'J''K'num > 0,那么对于那些行,您也将获得大于零的计数值。

答案 3 :(得分:0)

您可能应该做的就是修复数据模型,以便获得一个statuses参考表:

create tables statuses (
    status char(1) primary key,
    description varchar(255),
    createdAt datetime default curent_datetime
);

您可能还需要存储其他信息。

填充此表:

insert into statuses (status, description)
    values ('P', 'P status'),
           ('J', 'J status'),
           ('K', 'K status');

您可能会找到更好的描述。

声明适当的外键关系:

alter table base add constraint fk_base_status foreign key (status) references statuses(status);

然后使用left join

select s.status, count(b.status)
from statuses s left join
     base b
     on s.status = b.status
group by s.status;