Unique identifier for partition according to consecutive rows(根据连续行进行分区的唯一标识符)
本文介绍了根据连续行进行分区的唯一标识符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在处理一个需要分区的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以获取演示。
这篇关于根据连续行进行分区的唯一标识符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
沃梦达教程
本文标题为:根据连续行进行分区的唯一标识符


基础教程推荐
猜你喜欢
- Sql Server 字符串到日期的转换 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01