[英]How to add a category to the results of a query based on the output?
Extending this question for a more general case:将此问题扩展为更一般的情况:
I have a table called fruits
with a column fruit
that has three possible values: apple
, orange
, and mango
.我有一个名为
fruits
的表,其中的fruit
列具有三个可能的值: apple
、 orange
和mango
。 I used the following query to get the counts of each fruit
by date
:我使用以下查询按
date
获取每个fruit
的数量:
SELECT date, fruit, COUNT(id) AS count
FROM fruits
WHERE date BETWEEN '2020-10-02' AND '2020-10-05'
GROUP BY date, fruit
that gives the following results:给出以下结果:
date fruit count
--------------------------------
2020-10-02 apple 3
2020-10-02 orange 5
2020-10-03 orange 23
2020-10-03 mango 1
2020-10-04 mango 9
2020-10-05 apple 10
2020-10-05 orange 7
2020-10-05 mango 6
As you can see, not every date
contains each type of fruit
.如您所见,并非每个
date
都包含每种类型的fruit
。 Is it possible, and if so, how, to add the missing fruit by each date
to the above results with a default count=0
, as shown below?是否有可能,如果可以,如何使用默认
count=0
将每个date
丢失的水果添加到上述结果中,如下所示?
date fruit count
--------------------------------
2020-10-02 apple 3
2020-10-02 orange 5
2020-10-02 mango 0
2020-10-03 orange 23
2020-10-03 mango 1
2020-10-03 apple 0
2020-10-04 mango 9
2020-10-04 apple 0
2020-10-04 orange 0
2020-10-05 apple 10
2020-10-05 orange 7
2020-10-05 mango 6
Use a cross join
ot generate the row and then a left join
to bring in the results:使用
cross join
生成行,然后使用left join
来生成结果:
select d.date, f.fruit, coalesce(ff.count, 0) as count
from (select distinct date from fruits) d cross join
(select distinct fruit from fruits) f left join
fruits ff
on ff.date = d.date and ff.fruit = f.fruit;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.