Left Join无法按预期工作

时间:2014-04-16 15:45:48

标签: sql join outer-join

嗨,有帮助的聪明人,我在尝试准备查询时遇到了问题。我正在尝试将销售额和销售总额加入到预先构建的临时表中。

临时表(TMP_WEEK_SHOP)只有2行,周代码列表(WEEK_ID),然后是每个位置的代码(SHOP_ID)。

现在我的问题是,无论我做什么,如果在该周内没有该位置的销售,我的查询将始终省略临时表的结果。我需要输入每周的所有条目,甚至是0个销售店。

从我可以收集到的左外部联接应该给我这个,但无论我尝试过什么都不遗漏任何没有销售的商店。我应该说我在运行Server Management Studio的SQL Server 2005环境中运行。

任何帮助都会很棒!

USE CX
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='70006' or sal.SHOP_NUM='70008' or sal.SHOP_NUM='70010' or sal.SHOP_NUM='70018' or sal.SHOP_NUM='70028' or sal.SHOP_NUM='70029' or sal.SHOP_NUM='70012' or sal.SHOP_NUM='70016' or sal.SHOP_NUM='70026')
GROUP BY tws.WEEK_ID, tws.SHOP_ID
ORDER BY tws.WEEK_ID, tws.SHOP_ID

2 个答案:

答案 0 :(得分:1)

这是你的查询,格式化得更好,所以我可以阅读它:

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;

您有三个问题是“撤消”left outer joininner joinsal.STY_QUAL时,NULL条件将失败。很明显,where条件存在同样的问题。

您需要将所有联接设为left outer join并将where条件移至on条款:

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;

此外,count()永远不会返回NULL值,因此无需使用isnull()coalesce()

答案 1 :(得分:0)

您的其他加入onvolving CX_SALES_ITEMS sal也需要是左外连接