如何生成序列

时间:2016-09-20 11:06:29

标签: sql sql-server

+---+------------+
| V | output     |
+---+------------+
| y |          1 |
| y |          2 |
| y |          3 |
| N |          0 |
| y |          1 |
| y |          2 |
| N |          0 |
| N |          1 |
+---+------------+

2 个答案:

答案 0 :(得分:3)

我假设您有一个列(例如id),其中包含订购信息。然后,你想要识别出一起出现的" Y"和" N"以及然后枚举它们。

你可以使用行号技巧的差异来做到这一点:

select t.v,
       row_number() over (partition by v, seqnum_id - seqnum_vid order by id) as output
from (select t.*,
             row_number() over (order by id) as seqnum_id,
             row_number() over (partition v by order by id) as seqnum_vid
      from t
     ) t;

解释这是如何工作的通常是棘手的。我建议您运行子查询以查看序列号的外观以及为什么差异对于要识别的组是不变的。

答案 1 :(得分:0)

你的样本输出有点复杂,

我更倾向于使用SQL recursive query来解决您的问题 当然我假设id列从1开始并且连续地没有任何间隙。在更复杂的情况下,除了id字段之外还应该添加row_number()函数,并且应该在rownumbers上设置join

我希望它有所帮助,

--create table bool(id int identity(1,1), bool char(1))
--insert into bool values ('Y'),('N'),('Y'),('Y'),('Y'),('N'),('Y'),('N'),('N'),('Y'),('Y'),('Y'),('Y'),('Y'),('N'),('Y'),('Y')

;with cte as (
    select id, bool curr, bool pre, 1 output from bool where id = 1
    union all
    select 
        bool.id, bool.bool curr, cte.curr, 
        case when bool.bool = cte.curr then cte.output + 1 else case when bool.bool = 'Y' then 1 else 0 end end
    from cte
    inner join bool on bool.id = cte.id + 1
)
select * from cte

输出如下

enter image description here

相关问题