问题
I have four tables which are structured in a parent-child relation. One table has a primary key and the other three tables, otherwise unrelated to each other, have that primary key as a foreign key. That is, Table A has a primary key called customer ID. Tables B, C, and D also have customer ID and some other information.
What I want to achieve is to sum column2 of tables B, C, and D. I have tried:
SELECT dbo.a.primary_key,
SUM(dbo.b.column2) AS Expr1,
SUM(dbo.c.column2) AS Expr2,
SUM(dbo.d.column2) AS Expr3
FROM dbo.a
INNER JOIN dbo.b ON dbo.a.primary_key = dbo.b.column1
INNER JOIN dbo.c ON dbo.a.primary_key = dbo.c.column1
INNER JOIN dbo.d ON dbo.a.primary_key = dbo.d.column1
GROUP BY dbo.a.primary_key
This returns nothing. I have also tried a left outer join which returns nulls. I have also tried it with the below line, which is what I really want to achieve:
SUM(dbo.b.column2) + SUM(dbo.c.column2) + SUM(dbo.d.column2) AS Expr1
This may be down to poor design, as I could effectively join these three tables into one table, but believe it is tidier like this.
Once I have this problem solved, I would like to expand this as column3 of tables B, C, and D, so that they have a date field that is an int and links back to a date table (E). I would like to join tables A, B, C, and D to a newly created E at the same time, grouped by date and a.primary_key. Is this possible, or will I need to rethink the design?
回答1:
You can use APPLY instead of JOINs in case you just need to SELECT a single Column.
EDIT: If there are any NULL
values this query should get you a SUM
...
EDIT2: Changed the CROSS APPLY
to OUTER APPLY
, because in case one of the SUMS is non existent, the whole ROW will be dropped from the result.
SELECT a.primary_key,
b.Sum AS Expr1,
c.Sum AS Expr2,
d.Sum AS Expr3,
ISNULL(b.Sum, 0) + ISNULL(c.Sum, 0) + ISNULL(d.Sum, 0) as [GrandTotal]
FROM dbo.Agency_Table a
OUTER APPLY (SELECT SUM(ISNULL(b.column2, 0)) [Sum] FROM dbo.b WHERE a.primary_key = b.column1) as b
OUTER APPLY (SELECT SUM(ISNULL(c.column2, 0)) [Sum] FROM dbo.c WHERE a.primary_key = c.column1) as c
OUTER APPLY (SELECT SUM(ISNULL(d.column2, 0)) [Sum] FROM dbo.d WHERE a.primary_key = d.column1) as d
回答2:
The one clear thing from your example is that you accidentally put column names in your JOIN table names.
Change
INNER JOIN
dbo.b.column2
to
INNER JOIN
dbo.b
and the same for the other two.
来源:https://stackoverflow.com/questions/21149150/summing-common-columns-of-multi-table-parent-child-relation