Duplication involving SUM, LEFT JOIN and GROUP BY

前端 未结 3 1984
谎友^
谎友^ 2021-01-20 19:39

I have a problem involving a SUM, LEFT OUTER JOIN and GROUP BY commands, but can\'t figure out where my error is.

I have two tables, one for customer transactions an

3条回答
  •  走了就别回头了
    2021-01-20 19:55

    The query will be counting the transaction amount twice for 2007 due to the fact you have two claims, so the transaction amount will be counted twice.

    i.e. the returned data being used is:

    Customer | Transaction Year | Transaction Amount | Claim Amount
    ----------------------------------------------------------------
    A        | 2007             | 100                | 30
    A        | 2007             | 100                | 40
    A        | 2008             | 80                 |
    A        | 2008             | 50                 |
    A        | 2009             | 210                | 110
    

    Something like the following, although not pretty, should resolve the problem:

    SELECT 
       t.Customer
       ,t.Year
       ,[Transaction Amount] = SUM(t.[Transaction Amount])
       ,[Claim Amount] = c.[Claim Amount]
    FROM 
        Transactions t
        LEFT JOIN (
            SELECT 
                Customer
                ,Year
                ,SUM([Claim Amount])
            FROM
               Claims
            GROUP BY
               Customer, Year
        ) c ON c.Customer = t.Customer c.Year = t.Year
    GROUP BY t.Customer, t.Year, c.[Claim Amount]
    

提交回复
热议问题