【问题标题】:sql Find the pattern and count how many times it appearedsql 查找模式并计算它出现的次数
【发布时间】:2017-09-15 03:09:01
【问题描述】:

数据提供

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 是第三个模式。

【问题讨论】:

  • 你对“模式”的定义是什么?表中是否有另一列将定义序列?
  • 那是什么?微软 SQL Server 还是 PostgreSQL?这是两个非常不同的 DBMS。
  • 另外:什么定义了这些行的排序顺序?关系数据库中的行没有“排序”,因此如果您需要特定的行顺序,则需要一个列来排序。
  • 投票结束,因为不清楚问题是什么。
  • 我们正在使用红移

标签: sql amazon-redshift postgresql-8.0


【解决方案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

【讨论】:

  • 这是一个糟糕的解决方案,原因有两个:(1) 在这种结果格式中看不到模式。例如。没有任何迹象表明 id 12 和 id 13 属于同一模式。 (2) 这个结果可以通过更简单的代码select i,val from (select i,val ,lead(val) over (order by i) as lead_val from mytable ) t where val&lt;&gt;22 or lead_val&lt;&gt;22来实现
  • 是的,这是一个更简单的查询 - 我在确认中更新了我的答案。
【解决方案2】:

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 |
+-------------+--------+------+----------------+

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多