问题
Sorry about the title, but i couldn't think of a better subject for my issue.
I've two tables in a many-to-one relationship between them and an other many-to-one relatioshop in the same table. I need to sum a column that corresponds a aggregate from a column of first table.
Here is a image that illustrate what i want:
I have no idea how to proceed with this.
回答1:
This should do:
SELECT ISNULL(E.idParent,E.id) Id,
SUM(I.Value) [Sum]
FROM EXPENSE_TABLE E
LEFT JOIN INVOICE_TABLE I
ON I.idExpense = E.id
GROUP BY ISNULL(E.idParent,E.id)
For the updated requirement:
SELECT ISNULL(E.idParent,E.id) Id,
E2.[description],
SUM(I.Value) [Sum]
FROM EXPENSE_TABLE E
LEFT JOIN INVOICE_TABLE I
ON I.idExpense = E.id
INNER JOIN EXPENSE_TABLE E2
ON ISNULL(E.idParent,E.id) = E2.id
GROUP BY ISNULL(E.idParent,E.id),
E2.[description]
回答2:
You can get the results you are looking for by performing the aggregate sum operation on the results of the EXPENSE_TABLE joined to the INVOICE_TABLE.
For example:
SELECT e.idParent, SUM(i.value)
FROM EXPENSE_TABLE AS e
INNER JOIN INVOICE_TABLE AS i ON i.idExpense = e.id
GROUP BY e.idParent
ORDER BY e.idParent
来源:https://stackoverflow.com/questions/18990927/sum-a-column-that-corresponds-a-aggregate-from-a-column-of-another-table