有这样的几个问题,但我无法找到我特定问题的答案。
考虑下表:
| DateOfSale | food | customerid |
|---------------------------|--------------|------------|
| January, 03 2017 00:00:00 | pizza | 1 |
| January, 03 2017 00:00:00 | pizza | 2 |
| January, 03 2017 00:00:00 | pizza | 3 |
| January, 03 2017 00:00:00 | fish & chips | 4 |
| January, 02 2017 00:00:00 | pizza | 4 |
| January, 02 2017 00:00:00 | pizza | 4 |
| January, 02 2017 00:00:00 | pizza | 5 |
| January, 02 2017 00:00:00 | fish & chips | 6 |
| January, 01 2017 00:00:00 | pizza | 7 |
| January, 01 2017 00:00:00 | pizza | 8 |
| January, 01 2017 00:00:00 | pizza | 9 |
我们出售比萨饼和鱼类&芯片。
您会注意到我们并没有出售任何鱼类和鱼类。 1月1日的筹码在下面的结果,但我希望看到0的销售数量,但我不是。此外,1月4日没有销售记录,我希望披萨和鱼类都能看到0。芯片。这就是我从日期参考表中获取日期的原因 - 即使销售人员没有这个日期也存在。
| DateOfSale | food | Sales |
|---------------------------|--------------|-------|
| January, 01 2017 00:00:00 | pizza | 3 |
| January, 02 2017 00:00:00 | fish & chips | 1 |
| January, 02 2017 00:00:00 | pizza | 3 |
| January, 03 2017 00:00:00 | fish & chips | 1 |
| January, 03 2017 00:00:00 | pizza | 3 |
此结果的代码是:
SELECT DATE(d.thedate) as DateOfSale, f.food, count(s.customerid) as Sales
FROM ref_date d
LEFT JOIN sales s on d.thedate = s.saledate
INNER JOIN foods f on s.foodid = f.id
GROUP BY DATE(d.thedate), f.food
完整的数据小提琴在这里:http://sqlfiddle.com/#!9/ff9dc/2
答案 0 :(得分:1)
你走了:
SELECT d.thedate AS DateOfSale, f.Food, COUNT(s.customerid) AS Sales
FROM ref_date d
JOIN foods f
LEFT JOIN sales s ON s.saledate = d.thedate AND s.foodid = f.id
GROUP BY DateOfSale, Food;
输出:
| thedate | food | Sales | |---------------------------|--------------|-------| | January, 01 2017 00:00:00 | fish & chips | 0 | | January, 01 2017 00:00:00 | pizza | 3 | | January, 02 2017 00:00:00 | fish & chips | 1 | | January, 02 2017 00:00:00 | pizza | 3 | | January, 03 2017 00:00:00 | fish & chips | 1 | | January, 03 2017 00:00:00 | pizza | 3 | | January, 04 2017 00:00:00 | fish & chips | 0 | | January, 04 2017 00:00:00 | pizza | 0 |
答案 1 :(得分:0)
您可以cross join
包含所有可能日期的食物,然后离开加入销售表以获得0
次的行。
SELECT DATE(d.thedate) as DateOfSale, f.food, count(s.customerid) as Sales
FROM ref_date d
cross join foods f
LEFT JOIN sales s on s.saledate=d.thedate and s.foodid=f.id
GROUP BY DATE(d.thedate), f.food
order by 1,2