2017-04-19 90 views
-3

數據給sql中查找模式並計算有多少次出現

22 
22 
22 
22 
22 
36 
54 
40 
22 
22 
22 
22 
36 
22 
22 
54 
22 
22 

這是在表中的列。使用SQL查詢,我們需要找出圖案如 22 36 54 40是第一圖案然後22圖36是第二和22 54是第三圖案。

+1

什麼是你的一個 「模式」 的定義開始?表格中是否有另一列將定義序列? – Squirrel

+1

那是什麼? Microsoft SQL Server或PostgreSQL?這是兩個非常不同的DBMS。 –

+1

另外:什麼定義這些行的排序順序?在關係數據庫中的行不「排序」,所以如果你需要行的特定順序,你需要一個列進行排序的。 –

回答

1

您應該使用LEAD來獲取下一行的值,看看它是否是22,並使用它來擺脫列中所有額外的22。東西這種效果:

declare @t table (id int identity(1,1) not null, n int) 
insert into @t 
select 22 union all 
select 22 union all 
select 22 union all 
select 22 union all 
select 22 union all 
select 36 union all 
select 54 union all 
select 40 union all 
select 22 union all 
select 22 union all 
select 22 union all 
select 22 union all 
select 36 union all 
select 22 union all 
select 22 union all 
select 54 union all 
select 22 union all 
select 22 

select id,n from (select id,n ,lead(n) over (order by id) 
as lead_val from @t) t where n<>22 or lead_val<>22 

此輸出:

5 22 
6 36 
7 54 
8 40 
12 22 
13 36 
15 22 
16 54 
+0

這是因爲兩個原因一個壞的解決方案:**(1)**的模式不能在這個結果的格式可見。例如。沒有任何信息表明id 12和id 13屬於相同的模式。 **(2)**這個結果可以通過一個簡單得多的代碼來實現,選擇我,val from(select i,val ,lead(val)over(order by i)as lead_val from mytable )t 其中val <> 22 或lead_val <> 22' –

+0

是的,這是一個簡單的查詢 - 我我的答案更新確認。 –

0

的PostgreSQL

假設:

  • 有確定所述元素的順序的列
  • 種所有模式與22

select  array_to_string(array_agg(val order by i),',') as pattern 
      ,min (i)          as from_i 
      ,max (i)          as to_i 
      ,count(*)          as pattern_length   

from  (select i,val 
        ,count(case when val = 22 then 1 end) over 
        (
         order by i 
         rows unbounded preceding 
        ) as pattern_id 

      from mytable 
      ) t 

group by pattern_id 

having  count(*)>1 
; 

+-------------+--------+------+----------------+ 
| pattern | from_i | to_i | pattern_length | 
+-------------+--------+------+----------------+ 
| 22,36,54,40 |  5 | 8 |    4 | 
| 22,36  |  12 | 13 |    2 | 
| 22,54  |  15 | 16 |    2 | 
+-------------+--------+------+----------------+