问题
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