[英]How to add a category to the results of a query?
I have the following query:我有以下查询:
SELECT date, fruit, COUNT(id) AS count
FROM fruits
GROUP BY date, fruit
that gives the following results:这给出了以下结果:
date fruit count
--------------------------------
2020-10-03 apple 3
2020-10-03 orange 5
2020-10-04 apple 23
2020-10-04 orange 1
2020-10-05 apple 10
2020-10-05 orange 6
Is it possible, and if so, how, to add a new fruit to the above results mango
if it does not exist for every date
with count=0
, as shown below?如果
count=0
每个date
都不存在mango
,是否有可能,如果是,如何将新水果添加到上述结果mango
,如下所示?
date fruit count
--------------------------------
2020-10-03 apple 3
2020-10-03 orange 5
2020-10-03 mango 0
2020-10-04 apple 23
2020-10-04 orange 1
2020-10-04 mango 0
2020-10-05 apple 10
2020-10-05 orange 6
2020-10-05 mango 0
With UNION ALL
:与
UNION ALL
:
SELECT date, fruit, COUNT(id) AS count
FROM fruits
GROUP BY date, fruit
UNION ALL
SELECT DISTINCT f.date, 'mango', 0
FROM fruits f
WHERE NOT EXISTS (SELECT 1 FROM fruits WHERE date = f.date AND fruit = 'mango')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.