SQL Getting sum of all rows with Inner join and group by

廉价感情. 提交于 2021-01-29 09:24:10

问题


I am trying to get the sum of rows of the same DueDate. I'm joing 2 tables to populate other fields. However, I'm having difficulty aggregating the values on Amount column so that I can end up with one row for a specific DueDate The other columns all have the same value except the Amount and DueDate.

Below is my query

SELECT
T2.Company,
T2.Code
T2.DueDate,
SUM(T2.Amount)

FROM TBL2 T2 
LEFT JOIN
    TBL1 T1 
    ON T2.Company = T1.Company 
    AND T2.Code IN 
    (
       0, 1, 2, 3, 4, 5, 6, 7, 8
    )
GROUP BY
T1.Company,T2.Code,T2.DueDate,T2.Amount

When I run the query, I get :

Only the rows with DueDate of '20200604' is aggregated. (5000 + 5000 = 10000).

How do I aggregate and group by when values are different and when there's a table join?

I'd appreciate any help.

Thank you.


回答1:


Are you just looking for the right aggregation?

SELECT T2.Company, T2.Code T2.DueDate, SUM(T2.Amount)
FROM TBL2 T2 LEFT JOIN
     TBL1 T1 
     ON T2.Company = T1.Company AND
        T2.Code IN  0, 1, 2, 3, 4, 5, 6, 7, 8)
GROUP BY T1.Company, T2.Code, T2.DueDate;

That is AMOUNT does not belong in the GROUP BY.



来源:https://stackoverflow.com/questions/61660164/sql-getting-sum-of-all-rows-with-inner-join-and-group-by

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!