我有一个postgresql表,其中包含仓库之间不同项目(模型)的移动。
例如,以下记录表示已从仓库1到2发送了5个模型1单位:
source target model units
------ ------ ----- -----
1 2 1 5
我正在尝试构建SQL查询以获取发送和接收的单元之间的差异,按模型分组。再举一个例子:
source target model units
------ ------ ----- -----
1 2 1 5 -- 5 sent from 1 to 2
1 2 2 1
2 1 1 2 -- 2 sent from 2 to 1
2 1 1 1 -- 1 more sent from 2 to 1
结果应为:
source target model diff
------ ------ ----- ----
1 2 1 2 -- 5 sent minus 3 received
1 2 2 1
我想知道这是否可能使用单个SQL查询。
以下是表创建脚本和一些数据,以防万一有人想尝试:
CREATE TEMP TABLE movements
(
source INTEGER,
target INTEGER,
model INTEGER,
units INTEGER
);
insert into movements values (1,2,1,5);
insert into movements values (1,2,2,1);
insert into movements values (2,1,1,2);
insert into movements values (2,1,1,1);
答案 0 :(得分:4)
您可以使用两个子选择来对每个方向的运动求和,然后对这两个子查询的结果进行求和并求和:
SELECT source, target, model, SUM(units)
FROM (
SELECT source, target, model, SUM(units) AS units
FROM movements
WHERE source < target
GROUP BY source, target, model
UNION ALL
SELECT target, source, model, SUM(-units) AS units
FROM movements
WHERE source > target
GROUP BY source, target, model
) T1
GROUP BY source, target, model
答案 1 :(得分:1)
这可以满足您的需求吗?我没有要测试的Oracle数据库,所以我希望分组表达式的规则与MS SQL Server相同
SELECT
CASE WHEN source < target THEN source ELSE target END AS source,
CASE WHEN source < target THEN target ELSE source END AS target,
SUM(CASE WHEN source < target THEN units ELSE -units END) AS Diff,
model
FROM movements
GROUP BY
CASE WHEN source < target THEN source ELSE target END,
CASE WHEN source < target THEN target ELSE source END,
model