簡體   English   中英

在 SQL 服務器中搜索序列模式

[英]Search sequence pattern in SQL Server

我有這樣的記錄,我想在 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
======================================

用戶語音站點上有一個請求添加對 T-SQL 中行模式識別的支持(SQL:2016 功能 R010 和 R020) ,我相信這將允許這樣做。

與此同時,這應該做你需要的

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

如果您想要更靈活的方法,可以使用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';

是一個 db<>fiddle。

如果支持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';

但很可惜,事實並非如此。

如果我的要求正確,您可以嘗試在 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM