I created an SQL script for this problem . The trick is that B_QTY has appeared in your results more than once. To summarize, he gave artificially high value. So instead, run an extra select to use B_NAME only once! Great question !: ^ D
ABCade's answer is cool, but this solution will work for many databases. I have used this method before with SQL Server, Oracle, and Informix.
Data / Schemes:
create table a (A_ID int, A_NAME char(10)); create table b (B_ID int, A_ID int, B_NAME char(10), B_QTY int); create table c (C_ID int, B_ID int, C_QTY int); -- One dude insert into a values (1,'Xiezi'); -- 2 orders? of 4 and 3 insert into b values (1,1,'B1',20); insert into b values (2,1,'B1',5); insert into b values (3,1,'B1',5); insert into b values (4,1,'B2',5); -- 2 order with 2 lines each. insert into c values (1,1,3); insert into c values (2,1,4); insert into c values (4,2,2); insert into c values (5,2,1); insert into c values (6,3,1); insert into c values (7,4,1);
SQL (answer):
select a.A_ID, a.A_NAME, b.B_NAME, (select sum(b2.B_QTY) from b b2 where b2.B_NAME = b.B_NAME) as sum_b_qty, sum(c.C_QTY) from a left outer join b on b.A_ID = a.A_ID left outer join c on c.B_ID = b.B_ID group by a.A_ID, a.A_NAME, b.B_NAME order by a.A_ID ;
Output:
A_ID A_NAME B_NAME SUM_B_QTY SUM(C.C_QTY) 1 Xiezi B1 30 11 1 Xiezi B2 5 1