0

我有一个如下表:

group    sequence   action          
1        1          promotion_1               
1        2          promotion_1               
1        3          promotion_2               
1        4          act1                      
1        5          act1                     
1        6          act2                      
1        7          promotion_1               
1        8          act1                                  
1        9          act2                     
1       10          promotion_1               
1       11          act1                     
2        1          promotion_2                 
2        2          act1                  

我想创建一个排名,它将显示促销范围。所以我需要有相同的数字进行促销和促销后的每一个动作:

group    sequence   action         parameter   
1        1          promotion_1    1             
1        2          promotion_1    2              
1        3          promotion_2    3              
1        4          act1           3              
1        5          act1           3            
1        6          act2           3            
1        7          promotion_1    4            
1        8          act1           4                        
1        9          act2           4            
1       10          promotion_1    5            
1       11          act1           5           
2        1          promotion_2    1              
2        2          act1           1   

我阅读了有关窗口函数及其可能性的信息(例如 over()),但我只能通过“操作”创建分组排名。

4

2 回答 2

2
select T.*,
       sum(case when action like 'promotion%' then 1 else 0 end)
         over(partition by "group" order by sequence rows unbounded preceding) parameter
  from Table T
于 2017-05-03T18:06:26.093 回答
1

filter(从 PostgeSQL 9.4 开始)

select  *
       ,count (*) filter (where action like 'promotion%') over 
        (
            partition by  "group" 
            order by      sequence
            rows          unbounded preceding    
        )

from    mytable  T

+-------+----------+-------------+-------+
| group | sequence |   action    | count |
+-------+----------+-------------+-------+
|     1 |        1 | promotion_1 |     1 |
|     1 |        2 | promotion_1 |     2 |
|     1 |        3 | promotion_2 |     3 |
|     1 |        4 | act1        |     3 |
|     1 |        5 | act1        |     3 |
|     1 |        6 | act2        |     3 |
|     1 |        7 | promotion_1 |     4 |
|     1 |        8 | act1        |     4 |
|     1 |        9 | act2        |     4 |
|     1 |       10 | promotion_1 |     5 |
|     1 |       11 | act1        |     5 |
|     2 |        1 | promotion_2 |     1 |
|     2 |        2 | act1        |     1 |
+-------+----------+-------------+-------+
于 2017-05-03T18:21:35.947 回答