Michał Polowczyk
Michał Polowczyk

Reputation: 33

Numbering series of data in SQL

i have a little problem with SQL SELECT. I want to number continous groups of the same value in column nr 2: 1,'a' 2,'a, 3,'b' 4,'c' 5,'a' 6,'a' 7,'e' 8,'e'

The output i want :

1,'a',1 2,'a,,1 3,'b',2 4,'c',3 5,'a',4 6,'a',4 7,'e',5 8,'e',5

Is it possible to do it with just a select? I must do it in Vertica's SQL, its not supporting operations on variables in select, so i cant just declare a variable before and increment it somehow.

Upvotes: 1

Views: 129

Answers (2)

woot
woot

Reputation: 7616

You could use CONDITIONAL_CHANGE_EVENT() which is pretty simple. Basically you send in the column that you want to trigger the sequence increment as a parameter, and you order it the way you need it in the window. It's a Vertica analytic function.

SELECT col1, 
       col2,
       CONDITIONAL_CHANGE_EVENT(col2) OVER ( ORDER BY col1 )
FROM mytable

Upvotes: 3

Gordon Linoff
Gordon Linoff

Reputation: 1269953

You can do this with window functions. One method uses lag() and then does a cumulative sum of when the value changes:

select t.col1, t.col2,
       sum(case when col2 = prev_col2 then 0 else 1 end) over (order by col1) as newcol
from (select t.*,
             lag(col2) over (order by col1) as prev_col2
      from t
     ) t

Upvotes: 2

Related Questions