基于模式的sql查询

fiei3ece  于 2021-07-24  发布在  Java
关注(0)|答案(2)|浏览(235)

一张table:

col1          col2          col3           col4
17            5678          abc            mno
16            5678          abc            mno
15            5678          abc            mno
14            5678          abc            mno
13            5678          abc            mno
10            1234          def            pqr

我想创建一个列 output 值为“a”或“b”

col1          col2          col3           col4           output
 17            5678          abc            mno            b
 16            5678          abc            mno            a
 15            5678          abc            mno            b
 14            5678          abc            mno            b
 13            5678          abc            mno            a 
 10            1234          def            pqr            a

对于按列(或列组)划分的分区,即 col3, col4 订购方式 col1 and col2 ,输出被标记为“a”的值该组的第一次出现(例如第5行),该行标记一个可以连续持续3次的事件,之后再次出现 output 如果col1按顺序排列,则列应标记为“a”(例如,第2行)。

gzjq41n4

gzjq41n41#

ROW_NUMBER() 窗口功能:

select t.*,
  case mod(row_number() over (partition by t.col3, t.col4 order by t.col1, t.col2), 3) 
    when 1 then 'a'
    else 'b'
  end output
from tablename t 
order by t.col1 desc

请看演示。
结果:

> COL1 | COL2 | COL3 | COL4 | OUTPUT
> ---: | ---: | :--- | :--- | :-----
>   17 | 5678 | abc  | mno  | b     
>   16 | 5678 | abc  | mno  | a     
>   15 | 5678 | abc  | mno  | b     
>   14 | 5678 | abc  | mno  | b     
>   13 | 5678 | abc  | mno  | a     
>   10 | 1234 | def  | pqr  | a
njthzxwz

njthzxwz2#

这是一种缺口和孤岛问题。您需要枚举孤岛中的行,然后使用一些条件逻辑:

select t.*,
       (case when mod(row_number() over (partition by col3, col4, seqnum - seqnum_2 order by col1, col2), 3) = 1
             then 'a' else 'b'
        end) as
from (select t.*,
             row_number() over (order by col1, col2) as seqnum,
             row_number() over (partition by col3, col4 order by col1, col2) as seqnum_2
     from t
     ) t;

相关问题