左外连接增加SUM。如何预防呢?

时间:2019-07-18 22:09:50

标签: tsql ssms

以下简化的查询版本,但其基本要点:

WITH ClientSpend AS
    (
        SELECT
            c.ClientName
            , CONVERT(INT, (ROUND(SUM(CASE WHEN e.Type = 1 THEN e.Dollars ELSE 0 END), 0))) AS 1_Dollars
            , CONVERT(INT, (ROUND(SUM(CASE WHEN e.Type = 2 THEN e.Dollars ELSE 0 END), 0))) AS 2_Dollars
            -- There's a bunch more of these for different 'Types'
        FROM Expense e WITH(NOLOCK)
            INNER JOIN Client c WITH(NOLOCK)
                ON c.ClientID = e.ClientID
        GROUP BY c.ClientName
    )
SELECT
    ClientName
    , 1_Dollars
    , 2_Dollars
FROM ClientSpend
GROUP BY ClientName

类型2有其自己的Expense表,该表细分为CTE SELECT中最终CASE / SUM行所需的更详细的细节。

我尝试使用向该[ExpenseType2]表的LEFT JOIN来测试上述查询,并尽可能多地打开索引,并且我注意到2_Dollars上的SUM更高。我假设即使没有从[ExpenseType2]表中选择任何内容,它也会创建多条记录。

如何防止这种情况?

谢谢

1 个答案:

答案 0 :(得分:0)

为什么不使用子查询?还是简单的选择语句?或者,您可能需要使用样本数据来声明更多信息。

SELECT first_name, 1_Dollars, 2_Dollars FROM  
(
    SELECT
        c.ClientName
        , CONVERT(INT, (ROUND(SUM(CASE WHEN e.Type = 1 THEN e.Dollars ELSE 0 END), 0))) AS 1_Dollars
        , CONVERT(INT, (ROUND(SUM(CASE WHEN e.Type = 2 THEN e.Dollars ELSE 0 END), 0))) AS 2_Dollars
        -- There's a bunch more of these for different 'Types'
    FROM Expense e WITH(NOLOCK)
        INNER JOIN Client c WITH(NOLOCK)
            ON c.ClientID = e.ClientID
    GROUP BY c.ClientName
) a