I have SALES table of each days, its has an STOREID and the ITEMID with the DATE and GROSS
| DATE | STOREID | ITEMID | GROSS |
|------------ |--------- |-------- |------- |
| 2020-07-07 | STORE1 | ITEM1 | 10000 |
| 2020-07-07 | STORE2 | ITEM1 | 25000 |
| 2020-07-06 | STORE2 | ITEM3 | 15000 |
| 2020-07-06 | STORE3 | ITEM2 | 21000 |
The PRODUCT table show the category of the items, we have 5 items with 5 categories:
| ITEMID | CATEGORY |
|-------- |---------- |
| ITEM1 | A |
| ITEM2 | B |
| ITEM3 | C |
| ITEM4 | B |
| ITEM5 | D |
How can I select the revenue by storeid, itemid of each day with all of the category (if that day only sold category A, B then category C, D will show with gross is 0). Here the example of expected result when selecting the gross of July 7 for STORE1:
| DATE | STOREID | CATEGORY | GROSS |
|------------ |--------- |---------- |------- |
| 2020-07-07 | STORE1 | A | 10000 |
| 2020-07-07 | STORE1 | B | 0 |
| 2020-07-07 | STORE1 | C | 0 |
| 2020-07-07 | STORE1 | D | 0 |
I have tried:
SELECT distinct T.DATE, T.STOREID, P.CATEGORY, ISNULL(T.GROSS,0) AS GROSS
FROM PRODUCT P LEFT JOIN (
SELECT CONVERT(DATE, DATEID) AS DATE, STOREID, P.CATEGORY, convert(numeric(10,0), sum(S.GROSS)) AS GROSS
FROM SALES S join PRODUCT P on S.ITEMID = P.ITEMID
WHERE DATEID = '2020-07-07' and STOREID = 'STORE1'
GROUP BY P.CATEGORY, DATEID, STOREID
) T
ON P.CATEGORY = T.CATEGORY
The results I get is something like this:
| DATE | STOREID | CATEGORY | GROSS |
|------------ |--------- |---------- |------- |
| 2020-07-07 | STORE1 | A | 10000 |
| 2020-07-07 | STORE1 | B | 0 |
| NULL | NULL | C | 0 |
| NULL | NULL | D | 0 |
So when I execute the Query for others STORES and others days, how can I automated specify the correct value for the NULL value (like the expected result)
Thank you guys so much for your help!