根据连续行进行分区的唯一标识符 [英] Unique identifier for partition according to consecutive rows

查看:192
本文介绍了根据连续行进行分区的唯一标识符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在处理一个需要分区的SQL服务器查询,以便按日期排序的具有相同Type值的连续行具有相同的唯一标识符。 假设我有下表

declare @test table 
(
CustomerId  varchar(10),
Type INT,
date datetime
)

insert into @test values ('aaaa', 1,'2015-10-24 22:52:47')
insert into @test values ('bbbb', 1,'2015-10-23 22:56:47')
insert into @test values ('cccc', 2,'2015-10-22 21:52:47')
insert into @test values ('dddd', 2,'2015-10-20 22:12:47')
insert into @test values ('aaaa', 1,'2015-10-19 20:52:47')
insert into @test values ('dddd', 2,'2015-10-18 12:52:47')
insert into @test values ('aaaa', 3,'2015-10-18 12:52:47')
我希望我的输出列是这样的(数字不需要排序,我只需要每个组的唯一标识符): 编辑了原始帖子,因为我在所需的输出上犯了错误

0
0
1
1
2
3
4

免责声明:如果每行的CustomerID不同,则输出应该是相同的

,这与我的分区实际上并不相关

我当前的查询似乎做到了这一点,但它在某些情况下失败了,为具有不同类型值的行提供相同的ID。

SELECT row_number() over(order by date) - row_number() over (partition by  Type order by date)
FROM @TEST 

推荐答案

尝试如下内容:

declare @test table (
    CustomerId  varchar(10),
    Type INT,
    date datetime
)
insert into @test
values
    ('aaaa', 1,'2015-10-24 22:52:47'),
    ('bbbb', 1,'2015-10-23 22:56:47'),
    ('cccc', 2,'2015-10-22 21:52:47'),
    ('dddd', 2,'2015-10-20 22:12:47'),
    ('aaaa', 1,'2015-10-19 20:52:47'),
    ('dddd', 2,'2015-10-18 12:52:47'),
    ('aaaa', 3,'2015-10-18 12:52:47')
;

with cte as (
    select *, newtype = case when Type <> lag(Type) over(order by date desc) then 1 else 0 end
    from @test
)
select *,
    Result = sum(newtype) over(
        order by date desc
        rows between unbounded preceding and current row
        )
from cte
order by date desc

结果:

CustomerID 类型 日期 新类型 结果
aaaa 1 2015-10-24 22:52:47.000 0 0
bbbb 1 2015-10-23 22:56:47.000 0 0
CCCC 2 2015-10-22 21:52:47.000 1 1
dddd 2 2015-10-20 22:12:47.000 0 1
aaaa 1 2015-10-19 20:52:47.000 1 2
dddd 2 2015-10-18 12:52:47.000 1 3
aaaa 3 2015-10-18 12:52:47.000 1 4

公用表表达式(CTE)标记Type与以前不同的行。(第一行与Lag()=NULL的比较不会被标记为更改。)然后,主查询使用窗口求和对它们进行计数。

查看此db<>fiddle以获取演示。

这篇关于根据连续行进行分区的唯一标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆