For the below table:
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 pivot query:
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');
Which results:
+---------+-------+------+------+
| Date | santa | toy | tree |
+---------+-------+------+------+
| 2016-10 | 50 | 50 | 50 |
+---------+-------+------+------+
| 2016-12 | 8 | 5 | 15 |
+---------+-------+------+------+
Which works great, but I'd like to include all the months for a given interval even if there is no data for that month. So in the above example I'd 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 it possible with SQL?