1

I would like to count the number of sorted subgroups in the table below :

id  nmb
1   11
2   12
3   13
4   22
5   23
6   31
7   32
8   33
9   11
10  12
11  13
12  12
13  13
14  21
15  22
16  11
17  12
18  13
19  14

And want to obtain something like this in postgresql 8.4 :

id  nmb local  
1   11  1  
2   12  1  
3   13  1  
4   22  1  
5   23  1  
6   31  1  
7   32  1  
8   33  1  
9   11  2  
10  12  2  
11  13  2  
12  12  3  
13  13  3  
14  21  3  
15  22  3  
16  11  4  
17  12  4  
18  13  4  
19  14  4 

EDIT: the last few numbers on the 'local' column were wrong. Corrected!

Thank you.

4

3 回答 3

2

我虽然我终于明白了你想要什么,不断增长的价值观:

select id, nmb,
   sum(flag)
   over (order by id
         rows unbounded preceding) as local
from
 (
   select
      id, nmb,
      case
        when lag(nmb) 
             over (order by id) < nmb
          then 0 
        else 1
      end as flag
   from t
 ) as dt
order by id

但是第 4 组不适合

编辑:现在他们适合:-)

于 2013-09-17T19:43:04.813 回答
1

SQL小提琴

select
    id, nmb,
    row_number() over(partition by nmb order by id)
from t
order by id
于 2013-09-17T18:56:56.207 回答
1

您似乎正在尝试枚举组,其中组以低于nmb前一行的值开始(“前一个”由id订单定义)。

这个想法是通过使用来识别组的开始lag()。然后取累计和得到你想要的组标识符:

select id, nmb, sum(StartFlag) over (order by id) as local
from (select id, nmb,
             lag(nmb) over (order by id) as lastnmb,
             (case when lag(nmb) over (order by id) < nmb then 0
                   else 1
              end) as StartFlag
      from t
     ) t
order by id;
于 2013-09-17T19:41:40.733 回答