#### Calculate differences between rows while grouping with SQL

``````source target model units
------ ------ ----- -----
1      2     1     5
``````

``````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
``````

``````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);
``````
2 个回复

``````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
``````

``````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
``````
1 按行之间的差异对 SQL 进行分组？

2 sql计算2行之间的差异

4 如何计算pandas中分组行之间的差异

2020-07-03 17:53:40 2 58   pandas
5 计算分组行之间的最大差异

2015-02-12 09:03:09 5 174   sas
7 如何用SQL计算行之间的差异？

8 ACCESS / SQL：计算行之间的差异（不是日期）

9 带分组依据的两行之间的SQL差异

10 使用Case语句时计算分组计数

2020-12-22 17:08:10 1 24   case