加入收藏 | 设为首页 | 会员中心 | 我要投稿 52站长网 (https://www.52zhanzhang.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > MsSql教程 > 正文

SQL Server:行按组排序和序列

发布时间:2023-01-10 11:05:15 所属栏目:MsSql教程 来源:网络
导读: 我对似乎应该非常简单的东西感到困惑,但我现在太累了,现在不能再乱用了mssql 按关键字排序,所以我只是把它扔到这里看看是否有人可以展示如何去做这件事。 我试图做的是按照IDENTITY列(

我对似乎应该非常简单的东西感到困惑,但我现在太累了,现在不能再乱用了mssql 按关键字排序,所以我只是把它扔到这里看看是否有人可以展示如何去做这件事。 我试图做的是按照IDENTITY列(ID)按照组的顺序和表中的值所属的顺序确定表的行。 我正在使用Microsoft SQL Server 2008 R2 Management Studio(v10.50.4000.0)。SQL Server:行按组排序和序列

declare @X table (
ID int identity, 
Value varchar(20) 
); 
insert @X 
select 'abc' 
union all 
select 'zzz' --def 
union all 
select 'abc' 
union all 
select 'abc' 
union all 
select 'xyz' 
union all 
select 'abc' 
union all 
select 'abc'; 
select * from @X; 

最终的结果应该是这个样子:

/* 
*GO-GroupOrder; SO-SequenceOrder; GSO-GroupSequenceOrder 
ID Value GO SO GSO 
1 abc  1 1 1 
2 zzz  2 2 1 --def 
3 abc  1 3 2 
4 abc  1 3 2 
5 xyz  3 4 1 
6 abc  1 5 3 
7 abc  1 5 3 
*/ 

我希望这是可以接受的,我要的话,你的各种失败的尝试(包括ROW_NUMBER,等级,DENSE_RANK,组等),我迄今为止所做的......;我确信必须有一个相对简单的解决方案,不会涉及单个操作,但我无法弄清楚。 注意:编辑值定义为使zzz更清晰。 我希望这是有道理的,并提前感谢!

SOLUTION:

with 
    cte1 as (
     select 
      x.ID, 
      x.Value, 
      oX.ValuePrevious 
     from @X as x 
     outer apply (
      select 
       top 1 
        oX.Value as ValuePrevious 
      from @X as oX 
      where x.ID > oX.ID 
      order by oX.ID desc 
      ) as oX 
     ), 
    cte2 as (
     select 
      min(ID) as IDMin, 
      Value 
     from @x 
     group by Value 
     ), 
    cte3 as (
     select 
      cte1.ID, 
      cte1.Value, 
      dense_rank() over (order by cte2.IDMin) as [GO], 
      cCTE1.SO 
     from cte1 
     cross apply (
      select 
       sum(case 
        when 1 <> 1 
         or cCTE1.ValuePrevious != cCTE1.[Value] 
         or cCTE1.ValuePrevious is NULL 
        then 1 
        else 0 
        end) as SO 
      from cte1 as cCTE1 
      where cte1.ID >= cCTE1.ID 
      ) as cCTE1 
     join cte2 
      on cte2.Value = cte1.Value 
     ) 
    select 
     ID, 
     Value, 
     [GO], 
     SO, 
     dense_rank() over (partition by [GO] order by SO) as [GSO] 
    from cte3 order by ID; 

来源

2017-08-01Erg

(编辑:52站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!