sql - 需要在 SQL 中对值进行分组
问题描述
下面是我的表数据结构。
select 100 id, 1 srno,0 amt from dual
union all
select 100 id, 2 srno, 1000 amt from dual
union all
select 100 id, 3 srno, 1000 amt from dual
union all
select 100 id, 4 srno, 0 amt from dual
union all
select 100 id, 5 srno, 2000 amt from dual
我想要这样的结果,
ID From_Srno To_Srno amt
100 1 1 0
100 2 3 1000
100 4 4 0
100 5 5 2000
谢谢,名利
解决方案
这读作是一个间隙和孤岛问题,您希望将具有相同amt
.
我建议使用行号之间的差异来定义组:
select id, min(srno) from_srno, max(srno) max_srno, amt
from (
select t.*,
row_number() over(partition by id order by srno) rn1,
row_number() over(partition by id, amt order by srno) rn2
from mytable t
) t
group by id, amt, rn1 - rn2
身份证 | FROM_SRNO | MAX_SRNO | AMT --: | --------: | --------: | ---: 100 | 1 | 1 | 0 100 | 2 | 3 | 1000 100 | 4 | 4 | 0 100 | 5 | 5 | 2000
推荐阅读
- angularjs - 在组件angularjs中单击提交时调用父函数
- python - PyQt5 - 调整大小(限制最大大小)输入对话框
- css - 固定 JSF 页面对话框中按钮的位置
- javascript - 数据表隐藏/显示列
- javascript - 如何将状态传递给操作以获取 API?
- reactjs - 运行 npm 测试时 aws-amplify style.css 出错
- typescript - 从 onCreate 的 Firestore snap.data 检索数据但有未定义的错误
- c - C中嵌套结构的指针类型
- docker - 如何确保 Airflow 中的所有工作人员(容器)具有相同的环境?
- bash - 当 gofmt 建议更改时,让 gofmt 以退出状态 1 退出?