With the below table:
CREATE TABLE `STOCK_LEVEL`(
`ID` int(11),
`Date` date,
`ProductCode` varchar(50),
`Quantity` int(10)
)
INSERT INTO `STOCK_LEVEL` (`ID`, `Date`, `ProductCode`, `Quantity`) VALUES
(1, '2018-02-10', 'PROD01', 15),
(2, '2018-02-10', 'PROD02', 90),
(3, '2018-02-14', 'PROD03', 5),
(4, '2018-02-14', 'PROD01', 11);
I would like to see the stock level for a given product on a given day, so I have created a query by product:
SELECT
Date,
(Case when ProductCode = 'PROD01' then Quantity else 0 end) As 'AlphaProduct',
(Case when ProductCode = 'PROD02' then Quantity else 0 end) As 'BetaProduct',
(Case when ProductCode = 'PROD03' then Quantity else 0 end) As 'GammaProduct'
FROM STOCK_LEVEL
WHERE Date IN( '2018-02-10', '2018-02-14')
Which will give me a result like this:
+------------+--------------+-------------+--------------+
| Date | AlphaProduct | BetaProduct | GammaProduct |
+------------+--------------+-------------+--------------+
| 2018-02-10 | 15 | 0 | 0 |
+------------+--------------+-------------+--------------+
| 2018-02-10 | 0 | 90 | 0 |
+------------+--------------+-------------+--------------+
| 2018-02-14 | 0 | 0 | 5 |
+------------+--------------+-------------+--------------+
| 2018-02-14 | 11 | 0 | 0 |
+------------+--------------+-------------+--------------+
I am probably missing something basic, but is there a way to have this grouped by date like this: (I can't GROUP BY since there is no aggregate?)
+------------+--------------+-------------+--------------+
| Date | AlphaProduct | BetaProduct | GammaProduct |
+------------+--------------+-------------+--------------+
| 2018-02-10 | 15 | 90 | 0 |
+------------+--------------+-------------+--------------+
| 2018-02-14 | 11 | 0 | 5 |
+------------+--------------+-------------+--------------+