以下是我的表格:
AB元组表 具有A.id,B.id,C.units条目的C表 具有C.id条目的D表 我想计算D表中具有相同A.id和B.id的C.id的所有条目,并从具有相同A.id和B.id的所有C.units的总和中减去该计数。作为新栏目“差异”
所以我希望查询在一行中返回“差异”,常见A.id和公共B.id
如果计数为0并且“差异”将等于总和(C.units),它也应该返回一个条目
例如
D table
D.id = 1, open=true, D.CID = 2
D.id = 2, open=true, D.CID = 3
D.id = 3, open=true, D.CID = 3
D.id = 4, open=true, D.CID = 4
C table
C.id = 2, A.id = 3, B.id = 5, units =4
C.id = 3, A.id = 3, B.id = 5, units = 6
C.id = 4, A.id = 4, B.id = 6, units = 8
C.id = 5, A.id = 4, B.id = 6, units = 10
Bc D中的前3个条目具有相同AID和BID的CID,它们在同一条目中计数。此外,具有相同A.id和B.id的C条目的单位相加。即使C条目没有关联的D条目。因此,查询应返回以下两个条目:
1. difference = (6+4)-3 = 7 A.id = 3 B.id = 5
2. difference = (10+8)-1 = 17 A.id = 4 B.id = 6
答案 0 :(得分:1)
设置(你真的应该包含在你的问题中):
CREATE TABLE c
(
id int NOT NULL PRIMARY KEY,
aid int NOT NULL,
bid int NOT NULL,
units int NOT NULL
);
CREATE TABLE d
(
id int NOT NULL PRIMARY KEY,
open boolean NOT NULL,
cid int NOT NULL
);
INSERT INTO c VALUES (2,3,5,4),(3,3,5,6),(4,4,6,8),(5,4,6,10),(6,7,8,9);
INSERT INTO d VALUES (1,true,2),(2,true,3),(3,true,3),(4,true,4);
这个问题有点难以理解,但我认为你可能正在寻找这样的东西:
WITH n AS (
SELECT aid, bid, count(*) AS cnt
from c
JOIN d ON (d.cid = c.id)
GROUP BY aid, bid
)
SELECT aid, bid, sum(c.units) - COALESCE(n.cnt, 0) AS difference
FROM c
LEFT JOIN n USING (aid, bid)
GROUP BY aid, bid, n.cnt
ORDER BY aid, bid;
我得到了这些结果:
aid | bid | difference -----+-----+------------ 3 | 5 | 7 4 | 6 | 17 7 | 8 | 9 (3 rows)