SQL 将查询拆分为 start/end 并带有期望输出
SQL Query to split in start/end with desire output
我有一个 table 有以下记录
ItemCode
Value
1
0.000
1
0.290
1
0.370
1
0.650
1
1.190
1
2.120
1
2.700
1
2.900
1
7.360
2
2.340
2
2.790
2
2.890
2
3.500
2
3.600
3
2.100
3
2.250
3
3.000
我想输出如下
ItemCode
BeginNum
EndNum
1
0.000
0.290
1
0.290
0.370
1
0.370
0.650
1
0.650
1.190
1
1.190
2.120
1
2.120
2.700
1
2.700
2.900
1
2.900
7.360
2
2.340
2.790
2
2.790
2.890
2
2.890
3.500
2
3.500
3.600
3
2.100
2.250
3
2.250
3.000
你想要lead()
:
select *
from (
select itemcode, value as num,
lead(value) over(partition by itemcode order by value) as endnum
from mytable
) t
where endnum is not null
请注意,这会消除每组的最后一条记录,如示例数据所示。
你也可以这样做(如果你想要分组的最后一条记录,将'inner join'替换为'left outer join'):
with tablewithrow as (
select f1.*, row_number() over(partition by f1.ItemCode order by (select null)) rang
from mytable f1
)
select f1.ItemCode, f1.Value BeginNum, f2.Value EndNum
from tablewithrow f1
inner join tablewithrow f2 on f1.ItemCode=f2.ItemCode and f1.rang=f2.rang - 1
我有一个 table 有以下记录
ItemCode | Value |
---|---|
1 | 0.000 |
1 | 0.290 |
1 | 0.370 |
1 | 0.650 |
1 | 1.190 |
1 | 2.120 |
1 | 2.700 |
1 | 2.900 |
1 | 7.360 |
2 | 2.340 |
2 | 2.790 |
2 | 2.890 |
2 | 3.500 |
2 | 3.600 |
3 | 2.100 |
3 | 2.250 |
3 | 3.000 |
我想输出如下
ItemCode | BeginNum | EndNum |
---|---|---|
1 | 0.000 | 0.290 |
1 | 0.290 | 0.370 |
1 | 0.370 | 0.650 |
1 | 0.650 | 1.190 |
1 | 1.190 | 2.120 |
1 | 2.120 | 2.700 |
1 | 2.700 | 2.900 |
1 | 2.900 | 7.360 |
2 | 2.340 | 2.790 |
2 | 2.790 | 2.890 |
2 | 2.890 | 3.500 |
2 | 3.500 | 3.600 |
3 | 2.100 | 2.250 |
3 | 2.250 | 3.000 |
你想要lead()
:
select *
from (
select itemcode, value as num,
lead(value) over(partition by itemcode order by value) as endnum
from mytable
) t
where endnum is not null
请注意,这会消除每组的最后一条记录,如示例数据所示。
你也可以这样做(如果你想要分组的最后一条记录,将'inner join'替换为'left outer join'):
with tablewithrow as (
select f1.*, row_number() over(partition by f1.ItemCode order by (select null)) rang
from mytable f1
)
select f1.ItemCode, f1.Value BeginNum, f2.Value EndNum
from tablewithrow f1
inner join tablewithrow f2 on f1.ItemCode=f2.ItemCode and f1.rang=f2.rang - 1