我有这张桌子:
试图建立一个穷人的供应链。 我们收到有关操作的消息(R表示接收,S表示发送)。 每个位置都使用其ID码(SRC),发送或接收的数量以及目的地来报告。如果有人在发送,目的地就是货物的去向;如果有人在接收,目的地字段就是数据的来源。
唯一没有目的地的位置是HO(总部),因为它是根节点。
现在,我想报告差异。最近2笔交易(ID 21和22)分别缺少10和5个网。
我想联接数据,以便dest列与src列匹配,并查看QTYS和QTYR之间的区别。
我的SQL代码:
SELECT datas.SRC, datas.QTYR - datar.qtyS AS Difference
FROM data as datas JOIN data as datar on datas.dest = datar.src
WHERE datas.QTYR - datar.qtyS < 0 GROUP BY datas.src
数据库:
CREATE TABLE data (ID Int NOT NULL AUTO_INCREMENT, SRC NVARCHAR(20) NOT NULL, QTYR INT NOT NULL DEFAULT 0, QTYS INT NOT NULL DEFAULT 0, DEST NVARCHAR(20), OP NVARCHAR(20) NOT NULL, PRIMARY KEY(ID));
INSERT INTO DATA (SRC, QTYR, DEST, OP) VALUES ("HO01",1500000,"","R");
INSERT INTO DATA (SRC, QTYR, DEST, OP) VALUES ("HO02",1500000,"","R");
INSERT INTO DATA (SRC, QTYS, DEST, OP) VALUES ("HO01",750000,"DO01","S");
INSERT INTO DATA (SRC, QTYS, DEST, OP) VALUES ("HO01",750000,"DO02","S");
INSERT INTO DATA (SRC, QTYS, DEST, OP) VALUES ("HO02",750000,"DO03","S");
INSERT INTO DATA (SRC, QTYS, DEST, OP) VALUES ("HO02",750000,"DO04","S");
INSERT INTO DATA (SRC, QTYR, DEST, OP) VALUES ("DO01",750000,"HO01","R");
INSERT INTO DATA (SRC, QTYR, DEST, OP) VALUES ("DO02",750000,"HO01","R");
INSERT INTO DATA (SRC, QTYR, DEST, OP) VALUES ("DO03",750000,"HO02","R");
INSERT INTO DATA (SRC, QTYR, DEST, OP) VALUES ("DO04",750000,"HO02","R");
INSERT INTO DATA (SRC, QTYS, DEST, OP) VALUES ("DO01",375000,"HC01","S");
INSERT INTO DATA (SRC, QTYS, DEST, OP) VALUES ("DO02",375000,"HC02","S");
INSERT INTO DATA (SRC, QTYS, DEST, OP) VALUES ("DO03",375000,"HC03","S");
INSERT INTO DATA (SRC, QTYS, DEST, OP) VALUES ("DO04",375000,"HC04","S");
INSERT INTO DATA (SRC, QTYR, DEST, OP) VALUES ("HC01",375000,"DO01","R");
INSERT INTO DATA (SRC, QTYR, DEST, OP) VALUES ("HC02",375000,"DO02","R");
INSERT INTO DATA (SRC, QTYR, DEST, OP) VALUES ("HC03",375000,"DO03","R");
INSERT INTO DATA (SRC, QTYR, DEST, OP) VALUES ("HC04",375000,"DO04","R");
INSERT INTO DATA (SRC, QTYS, DEST, OP) VALUES ("HC01",100000,"DP01","S");
INSERT INTO DATA (SRC, QTYS, DEST, OP) VALUES ("HC01",100000,"DP02","S");
INSERT INTO DATA (SRC, QTYR, DEST, OP) VALUES ("DP01",99990,"HC01","R");
INSERT INTO DATA (SRC, QTYR, DEST, OP) VALUES ("DP02",99995,"HC01","R");
答案 0 :(得分:1)
我认为该查询解决了您的问题:
select *,
qtyr-qtys as Diff
from (
select SRC, sum(QTYR) as qtyr
from data s
group by SRC
) s
join (
select DEST, sum(QTYS) as qtys
from data s
group by DEST
) d
ON s.SRC=d.DEST
where qtyr!=qtys
它只是对发送的金额,接收的金额进行总计,分别按发送者/接收者分组,然后检查数字是否匹配。 请注意,您要按两个不同的概念分组,首先按发送者,然后按接收者。这可能是您查询的问题。