【问题标题】:SQL Query to split in start/end with desire output [closed]SQL查询以期望输出开始/结束分割[关闭]
【发布时间】:2020-12-21 17:51:41
【问题描述】:

我有一张包含以下记录的表格

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

【问题讨论】:

  • 对不起,我应该发布我尝试过的查询。这是我的第一篇文章。会记住以后的帖子。谢谢!

标签: sql-server sql-server-2016


【解决方案1】:

你想要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

请注意,这会消除每组的最后一条记录,如您的示例数据所示。

【讨论】:

    【解决方案2】:

    您也可以这样做(如果您想要按组记录最后一条记录,请将“内连接”替换为“左外连接”):

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-03-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多