sql - 找出两行之间的差异
问题描述
我需要找到下表中 c2 行之间的差异
SEQ_ID Priv_ID Common_ID Source_ID C1 C2
------ -------- --------- --------- -- ---
1 1 C001 S1 abc 32331299300
2 1 C001 S1 def 12656678121
3 1 C001 S1 ghi 8966492700
4 1 C001 S2 abc 32331292233
5 1 C001 S2 ghi 8966492700
6 1 C001 S2 def 12656672000
预期输出应如下所示,
SEQ_ID Priv_ID Common_ID C1 C2
------ -------- --------- -- ---
1 1 C001 abc 7067
2 1 C001 def 6121
3 1 C001 ghi 0
请协助。
解决方案
这个怎么样?我没有对所有行使用相同的列(所以它们没有任何区别)。
SQL> with test (seq_id, source_id, c1, c2) as
2 (select 1, 's1', 'abc', 32331299300 from dual union all
3 select 2, 's1', 'def', 12656678121 from dual union all
4 select 3, 's1', 'ghi', 8966492700 from dual union all
5 select 4, 's2', 'abc', 32331292233 from dual union all
6 select 5, 's2', 'ghi', 8966492700 from dual union all
7 select 6, 's2', 'def', 12656672000 from dual
8 )
9 select min(seq_id) seq_id,
10 c1,
11 max(case when source_id = 's1' then c2 end) +
12 max(case when source_id = 's2' then -c2 end) c2
13 from test
14 group by c1
15 order by 1;
SEQ_ID C1 C2
---------- --- ----------
1 abc 7067
2 def 6121
3 ghi 0
SQL>
推荐阅读
- r - 根据特定列中的值将值分配给特定单元格
- c++ - 在赋值运算符中调用复制构造函数,需要左值作为赋值的左操作数
- office-js - Office.js Outlook 加载项 InternetHeaders Prefer ImmutableId
- html - 我的 foreach 循环不像以前那样工作
- python - 如何在数据框 Pandas 中插入数据框
- matlab - 用于组合文件夹中的 .fig 文件以生成视频/动画的 MATLAB 代码?
- mysql - 为每个成员返回顶部字段的 SQL 查询
- c# - Dev Express Extreme Grid - 通过 IF 条件添加列属性
- xpath - 在 Jmeter 中使用 Xpath 提取器捕获响应
- r - 如何从数据框中绘图?