正确的外部加入没有返回预期的行?

时间:2014-03-26 17:15:57

标签: sql sql-server

我正在尝试使用以下连接两个表的SQL Server查询返回预测接口的.NET数据表:

SELECT accounts.AccountID
,accounts.Account
,SUM(CASE 
        WHEN forecast.omonth = 1
            THEN forecast.ns1
        ELSE 0
        END) / 1 Jan
,SUM(CASE 
        WHEN forecast.omonth = 2
            THEN forecast.ns1
        ELSE 0
        END) / 1 Feb
,SUM(CASE 
        WHEN forecast.omonth = 3
            THEN forecast.ns1
        ELSE 0
        END) / 1 Mar
,SUM(CASE 
        WHEN forecast.omonth = 4
            THEN forecast.ns1
        ELSE 0
        END) / 1 Apr
,SUM(CASE 
        WHEN forecast.omonth = 5
            THEN forecast.ns1
        ELSE 0
        END) / 1 May
,SUM(CASE 
        WHEN forecast.omonth = 6
            THEN forecast.ns1
        ELSE 0
        END) / 1 Jun
,SUM(CASE 
        WHEN forecast.omonth = 7
            THEN forecast.ns1
        ELSE 0
        END) / 1 Jul
,SUM(CASE 
        WHEN forecast.omonth = 8
            THEN forecast.ns1
        ELSE 0
        END) / 1 Aug
,SUM(CASE 
        WHEN forecast.omonth = 9
            THEN forecast.ns1
        ELSE 0
        END) / 1 Sep
,SUM(CASE 
        WHEN forecast.omonth = 10
            THEN forecast.ns1
        ELSE 0
        END) / 1 Oct
,SUM(CASE 
        WHEN forecast.omonth = 11
            THEN forecast.ns1
        ELSE 0
        END) / 1 Nov
,SUM(CASE 
        WHEN forecast.omonth = 12
            THEN forecast.ns1
        ELSE 0
        END) / 1 Dec
FROM accountForecast forecast
RIGHT OUTER JOIN account_tree accounts ON forecast.AccountID = accounts.AccountID
WHERE forecast.oYear = 2014
AND accounts.AccountID in (35, 36, 37, 38, 39, 40, 41, 78, 79, 80, 81, 1, 82, 176)
GROUP BY accounts.AccountID
    ,accounts.Account

accountForecast表的结构如下: enter image description here

此查询应为WHERE子句(35,36,37等)中的所有帐户ID返回一行,即使给定帐户在accountForecast表中没有条目,在这种情况下查询应返回0。

我的查询当前只返回一行,其中包含已插入accountForecast表中的AccountID。我加入不正确吗?我应该改变什么?

编辑:我删除了forecast.oYear = 2014 WHERE子句,它似乎按预期工作。但是,重要的是这个查询是由year参数提供的,因为数据依赖于它。有没有办法在指定年份的同时返回所有帐户行?

2 个答案:

答案 0 :(得分:2)

您的过滤器会排除NULL的值:

WHERE forecast.oYear = 2014

答案 1 :(得分:1)

很难理解您的数据实际存储位置,但我假设所有帐户都存储在account_tree中?如果是,请尝试撤消FROMJOIN条款:

FROM account_tree accounts 
RIGHT OUTER JOIN accountForecast forecast ON forecast.AccountID = accounts.AccountID
WHERE forecast.oYear = 2014
AND accounts.AccountID in (35, 36, 37, 38, 39, 40, 41, 78, 79, 80, 81, 1, 82, 176)
GROUP BY accounts.AccountID
    ,accounts.Account