This is your query, formatted a bit better so I can read it:
SELECT tws.WEEK_ID as Week, isnull(tws.SHOP_ID,0)as Shop,
isnull(count(sal.SALES_ITEMS_ID),0)Sales, isnull(sum(sal.LINEVALUE),0)Sales_Value
FROM TMP_WEEK_SHOP tws JOIN
CX_DATES dat
on dat.WEEK_ID = tws.WEEK_ID LEFT OUTER JOIN
CX_SALES_ITEMS sal
on sal.DATE_ID = dat.DATE_ID and
sal.SHOP_NUM = tws.SHOP_ID JOIN
CX_STYLES sty
on sal.STY_QUAL = sty.STY_QUAL
WHERE sty.STY_RET_TYPE='BIKES' and
(sal.SHOP_NUM in ('70006', '70008', '70010', '70018', '70028', '70029', '70012', '70016', '70026')
GROUP BY tws.WEEK_ID, tws.SHOP_ID
ORDER BY tws.WEEK_ID, tws.SHOP_ID;
You have three problems that are "undoing" the left outer join
. The inner join
condition will fail when sal.STY_QUAL
is NULL
. SImilarly, the where
conditions have the same problem.
You need for all the joins to be left outer join
s and to move the where
conditions to on
clauses:
SELECT tws.WEEK_ID as Week, isnull(tws.SHOP_ID,0)as Shop,
isnull(count(sal.SALES_ITEMS_ID),0)Sales, isnull(sum(sal.LINEVALUE),0)Sales_Value
FROM TMP_WEEK_SHOP tws JOIN
CX_DATES dat
on dat.WEEK_ID = tws.WEEK_ID LEFT OUTER JOIN
CX_SALES_ITEMS sal
on sal.DATE_ID = dat.DATE_ID and
sal.SHOP_NUM = tws.SHOP_ID and
sal.SHOP_NUM in ('70006', '70008', '70010', '70018', '70028', '70029', '70012', '70016', '70026'
) LEFT OUTER JOIN
CX_STYLES sty
on sal.STY_QUAL = sty.STY_QUAL and
sty.STY_RET_TYPE='BIKES'
GROUP BY tws.WEEK_ID, tws.SHOP_ID
ORDER BY tws.WEEK_ID, tws.SHOP_ID;
In addition, count()
never returns a NULL
value, so using isnull()
or coalesce()
is unnecessary.