In the table below:
CREATE TABLE products
(
date DATE,
productname VARCHAR(80),
quantity INT(5)
);
INSERT INTO `products`(`date`, `productname`, `quantity`) VALUES ('2016-12-16','toy',5);
INSERT INTO `products`(`date`, `productname`, `quantity`) VALUES ('2016-12-18','santa',8);
INSERT INTO `products`(`date`, `productname`, `quantity`) VALUES ('2016-12-23','tree',15);
INSERT INTO `products`(`date`, `productname`, `quantity`) VALUES ('2016-10-01','toy',10);
INSERT INTO `products`(`date`, `productname`, `quantity`) VALUES ('2016-10-04','santa',20);
INSERT INTO `products`(`date`, `productname`, `quantity`) VALUES ('2016-10-09','tree',30);
INSERT INTO `products`(`date`, `productname`, `quantity`) VALUES ('2016-10-01','toy',40);
INSERT INTO `products`(`date`, `productname`, `quantity`) VALUES ('2016-10-04','santa',30);
INSERT INTO `products`(`date`, `productname`, `quantity`) VALUES ('2016-10-09','tree',20)
I have the following summary request:
SELECT DATE_FORMAT(`date`, '%Y-%m') As Date,
IFNULL(Sum(Case when `productname` = 'santa' then `quantity` end),0) As santa,
IFNULL(Sum(Case when `productname` = 'toy' then `quantity` end),0) As toy,
IFNULL(Sum(Case when `productname` = 'tree' then `quantity` end),0) As tree
FROM `products`
WHERE `Date` BETWEEN '2016-10' and '2016-12'
GROUP BY DATE_FORMAT(`date`, '%Y-%m');
What are the results:
+---------+-------+------+------+
| Date | santa | toy | tree |
+---------+-------+------+------+
| 2016-10 | 50 | 50 | 50 |
+---------+-------+------+------+
| 2016-12 | 8 | 5 | 15 |
+---------+-------+------+------+
Which works fine, but I would like to include all months for a given interval, even if there is no data in this month. Therefore, in the above example, I would like to have this, as a result:
+---------+-------+------+------+
| Date | santa | toy | tree |
+---------+-------+------+------+
| 2016-10 | 50 | 50 | 50 |
+---------+-------+------+------+
| 2016-11 | 0 | 0 | 0 |
+---------+-------+------+------+
| 2016-12 | 8 | 5 | 15 |
+---------+-------+------+------+
Is this possible with SQL?