Sum a column that corresponds a aggregate from a column of another table

余生长醉 提交于 2019-12-11 22:17:14

问题


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

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