sql - PostgresSQL rank query -


i have data in postgresql table follows,

pkid  id  timestamp              isactive -----------------------------------------    1  1   "2013-08-08 10:10:10"  0    2  1   "2013-08-08 10:11:10"  0    3  1   "2013-08-08 10:12:10"  0    4  1   "2013-08-08 10:13:10"  1    5  1   "2013-08-08 10:14:10"  1    6  1   "2013-08-08 10:15:10"  1    7  1   "2013-08-08 10:16:10"  1    8  1   "2013-08-08 10:17:10"  1    9  1   "2013-08-08 10:18:10"  0   10  1   "2013-08-08 10:19:00"  0   11  2   "2013-08-08 09:10:10"  0 

i want query first record when changes active inactive state or vice versa, eg each id,

   1  1   "2013-08-08 10:10:10"  0    4  1   "2013-08-08 10:13:10"  1    9  1   "2013-08-08 10:18:10"  0   11  2   "2013-08-08 09:10:10"  0 

i tried using rank() assign rank value across active/inactive, ie rank() (partition id,isactive order timestamp)

 pkid id  timestamp             isactive  rank  ----------------------------------------------     1 1  "2013-08-08 10:10:10"   0        1     2 1  "2013-08-08 10:11:10"   0        2     3 1  "2013-08-08 10:12:10"   0        3     4 1  "2013-08-08 10:13:10"   1        1     5 1  "2013-08-08 10:14:10"   1        2     6 1  "2013-08-08 10:15:10"   1        3     7 1  "2013-08-08 10:16:10"   1        4     8 1  "2013-08-08 10:17:10"   1        5     9 1  "2013-08-08 10:18:10"   0        4    10 1  "2013-08-08 10:19:00"   0        5    11 2  "2013-08-08 09:10:10"   0        1 

i see result as,

pkid  id timestamp              isactive rank ---------------------------------------------    1  1  "2013-08-08 10:10:10"  0         1    2  1  "2013-08-08 10:11:10"  0         2    3  1  "2013-08-08 10:12:10"  0         3    4  1  "2013-08-08 10:13:10"  1         1    5  1  "2013-08-08 10:14:10"  1         2    6  1  "2013-08-08 10:15:10"  1         3    7  1  "2013-08-08 10:16:10"  1         4    8  1  "2013-08-08 10:17:10"  1         5    9  1  "2013-08-08 10:18:10"  0         1   10  1  "2013-08-08 10:19:00"  0         2   11  2  "2013-08-08 09:10:10"  0         1 

i can pick rank ==1 , timestamp when state changed.

you can using lag() function:

select t.* (select t.*,              lag(isactive) on (partition id order timestamp) previsactive       t      ) t previsactive null or previsactive <> isactive; 

you can way suggested if state goes in 1 direction -- inactive active or vice versa. method combines actives , inactives id, resulting in continuous numbering.


Comments

Popular posts from this blog

scala - 'wrong top statement declaration' when using slick in IntelliJ -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

PySide and Qt Properties: Connecting signals from Python to QML -