我对SQL不是很熟悉。我正在使用oracle。我遇到了一个关于总结字段的问题。
以下是示例表:
A:
A_ID
A_NAME
B:
B_ID
A_ID
B_NAME
B_QTY
C:
C_ID
B_ID
C_QTY
所以数据结构就像A - > * B - > * C
我需要获得按B_NAME和A_ID分组的B和C总数。例如:
A:
A_ID A_NAME
1 A1
B:
B_ID A_ID B_NAME B_QTY
1 1 B1 20
2 1 B1 5
3 1 B1 5
4 1 B2 5
C:
C_ID B_ID C_QTY
1 1 3
2 1 4
4 2 2
5 2 1
6 3 1
7 4 1
预期结果是:
A_ID A_NAME B_NAME B_QTY C_QTY
1 A1 B1 30 11
1 A1 B2 5 1
第1行中B_QTY的30是20 + 5 + 5的结果。
第1行中的C_QTY 11是3 + 4 + 2 + 1 + 1的结果。
这是我的sql:
select a.A_ID,
a.A_NAME,
b.B_NAME
sum(b.B_QTY),
sum(c.C_QTY)
from A a left outer join B b on b.A_ID = a.A_ID
left outer join C c on c.B_ID = b.B_ID
group by a.A_ID
order by a.A_ID, b.B_NAME
where a.XXXX = XXXXX;
所以问题是:
由于B映射到多个C,因此B_QTY将被多次求和。我对SQL不是很熟悉所以我不知道是否有任何简单的方法可以根据某些字段(在我的例子中是B_ID)来区分求和。谢谢!
答案 0 :(得分:2)
这也可以这样做:
WITH b2 AS
(SELECT b.*, sum(b.b_qty) over (partition BY b.a_id, b.b_name) b_qty_s
FROM b)
SELECT a.a_id, a.a_name, b2.b_name, b2.b_qty_s, sum(c.c_qty) c_qty_s
FROM a JOIN b2 ON a.a_id = b2.a_id
JOIN c ON b2.b_id = c.b_id
GROUP BY a.a_id,a.a_name, b2.b_name, b2.b_qty_s
答案 1 :(得分:1)
我创建了 SQL fiddle for this problem 。诀窍是B_QTY不止一次出现在你的结果中。总结它是一个人为的高价值。因此,运行子选择仅使用B_NAME一次!好问题! :^ d
A.B.Cade的答案很酷,但这个解决方案适用于许多数据库。我以前在SQL Server,Oracle和Informix中使用过这种技术。
数据/模式:
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(答案):
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
;
输出:
A_ID A_NAME B_NAME SUM_B_QTY SUM(C.C_QTY)
1 Xiezi B1 30 11
1 Xiezi B2 5 1
答案 2 :(得分:1)
你也可以这样做:
SELECT DISTINCT A_ID,A_NAME,B_NAME,B_SUM,SUM(C_QTY) OVER(PARTITION BY A_NAME,B_NAME) C_SUM
FROM (
SELECT A.A_ID,A_NAME,B_NAME,B_ID,SUM(B_QTY) OVER(PARTITION BY A_NAME,B_NAME) B_SUM
FROM A JOIN B
ON A.A_ID=B.A_ID) T1
JOIN C
ON T1.B_ID=C.B_ID