简体   繁体   中英

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.

======================================
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.

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 :

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.

If string_agg() were supported as a window function, you could use:

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-

DEMO HERE

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM