[英]Search sequence pattern in SQL Server
I have records like this and I want to search in SQL Server by pattern and sequence like (50,54,50) in value field it should return 02,03,04 any one have idea to do this.我有这样的记录,我想在 SQL 服务器中按模式和序列(如(50,54,50))在值字段中搜索它应该返回 02,03,04 任何人都知道这样做。
======================================
Id Date Value
01 2020-01-01 50
02 2020-01-02 50
03 2020-01-03 54
04 2020-01-04 50
05 2020-01-05 35
06 2020-01-06 98
07 2020-01-07 13
======================================
There is a request on the user voice site Add support for Row Pattern Recognition in T-SQL (SQL:2016 features R010 and R020) which I believe would allow for this.用户语音站点上有一个请求添加对 T-SQL 中行模式识别的支持(SQL:2016 功能 R010 和 R020) ,我相信这将允许这样做。
In the meantime this should do what you need与此同时,这应该做你需要的
WITH T AS
(
SELECT *,
LAG(Id) OVER (ORDER BY Id) AS PrevId,
LAG(value) OVER (ORDER BY Id) AS PrevValue,
LEAD(Id) OVER (ORDER BY Id) AS NextId,
LEAD(value) OVER (ORDER BY Id) AS NextValue
FROM YourTable
)
SELECT PrevId, Id, NextId
FROM T
WHERE PrevValue = 50 AND Value =54 AND NextValue = 50
If you wanted a more flexible approach, you can use cross apply
:如果您想要更灵活的方法,可以使用
cross apply
:
select t2.*
from t cross apply
(select string_agg(id, ',') within group (order by date) as ids,
string_agg(value, ',') within group (order by date) as vals
from (select top (3) t2.*
from t t2
where t2.date >= t.date
order by t2.date
) t2
) t2
where vals = '50,54,50';
Here is a db<>fiddle. 这是一个 db<>fiddle。
If string_agg()
were supported as a window function, you could use:如果支持
string_agg()
作为 window function,您可以使用:
select t.*
from (select t.*,
string_agg(id, ',') within group (order by date) over (order by id rows between current row and 2 following) as ids,
string_agg(value, ',') within group (order by date) over (order by id rows between current row and 2 following) as vals
from t
) t
where vals = '50,54,50';
But alas, it is not.但很可惜,事实并非如此。
If I get your requirement correct, yo can try this below logic developed with the help of LAG and LEAD-如果我的要求正确,您可以尝试在 LAG 和 LEAD 的帮助下开发的以下逻辑-
WITH CTE
AS
(
SELECT Id,Date,
LAG(value,2) OVER(ORDER BY id) lag_2,
LAG(value,1) OVER(ORDER BY id) lag_1,
Value c_val,
LEAD(value,1) OVER(ORDER BY id) lead_1,
LEAD(value,2) OVER(ORDER BY id) lead_2
FROM your_table
)
SELECT Id,Date,
CASE
WHEN (lag_2 = 50 AND lag_1 = 54 AND c_val = 50) OR
(lag_1 = 50 AND c_val = 54 AND lead_1 = 50) OR
(c_val = 50 AND lead_1 = 54 AND lead_2 = 50)
THEN (
CASE
WHEN lead_1 = 54 THEN 02
WHEN c_val = 54 THEN 03
WHEN lag_1 = 54 THEN 04
END
)
ELSE c_val
END
FROM CTE
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.