使用 SQL Server 获取列中第一次出现重复值的行 [英] Get the row with first occurrence of repetitive value in column using SQL Server

查看:39
本文介绍了使用 SQL Server 获取列中第一次出现重复值的行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有这张桌子

Id   Order Value
------------------
aa   0     'cat'
ba   1     'dog'
bb   2     'yuk'
dc   3     'gen'
ca   4     'cow'
c1   5     'owl'
b0   7     'ant'
h9   8     'fly'
t4   9     'bee'
g2   10    'fox'
ea   11    'rat'
fa   12    'pig'
gu   13    'pig'
co   14    'pig'
fo   15    'pig'
ou   16    'pig'
eo   17    'pig'
ii   18    'pig'

查询是为了获得什么:

fa   12    'pig'

如您所见,12 到 18 之间的下一行.所有这些行在 Value 列中都有一个 pig.

Like you can see, the next rows after 12 till 18. All these rows have a pig in the Value column.

如何确定重复开始的行?

How determine the row where the repetition began?

谢谢

推荐答案

您可以将 WITH TIES 选项与窗口函数 lead() 一起使用>row_number()

You can use the WITH TIES option in concert with the window functions lead() and row_number()

示例

Declare @YourTable Table ([Id] varchar(50),[Order] int,[Value] varchar(50))  Insert Into @YourTable Values 
 ('aa',0,'cat')
,('ba',1,'dog')
,('bb',2,'yuk')
,('dc',3,'gen')
,('ca',4,'cow')
,('c1',5,'owl')
,('b0',7,'ant')
,('h9',8,'fly')
,('t4',9,'bee')
,('g2',10,'fox')
,('ea',11,'rat')
,('fa',12,'pig')
,('gu',13,'pig')
,('co',14,'pig')
,('fo',15,'pig')
,('ou',16,'pig')
,('eo',17,'pig')
,('ii',18,'pig')
 
Select top 1 with ties *
 From @YourTable
 Order By case when lead(value,1) over (order by [order]) = value then 1 else 2 end
         ,row_number() over (order by [Order])

结果

Id  Order   Value
fa  12      pig

这篇关于使用 SQL Server 获取列中第一次出现重复值的行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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