2013-08-29 13 views
5

ho una struttura di tabella come di seguitocome sequenza gorups numero sub

id wstage  wstatus wdate 
101 Unaquired create 2013-08-29 17:07:20.040 
101 Unaquired rework 2013-08-29 18:07:20.040 
101 inprocess accqui 2013-08-29 19:07:20.040 
101 inprocess alloca 2013-08-29 20:07:20.040 
101 Unaquired create 2013-08-29 21:07:20.040 
101 Unaquired rework 2013-08-29 22:07:20.040 

devo annoverare questo come

id wstage  wstatus wdate     rownumber 
101 Unaquired rework 2013-08-29 22:07:20.040 1 
101 Unaquired create 2013-08-29 21:07:20.040 1 
101 inprocess alloca 2013-08-29 20:07:20.040 2 
101 inprocess accqui 2013-08-29 19:07:20.040 2 
101 Unaquired rework 2013-08-29 18:07:20.040 3 
101 Unaquired create 2013-08-29 17:07:20.040 3 

Sto cercando di utilizzare la funzione

select *,ROW_NUMBER() over (partition by id,wstage order by wdate desc) rownumber 

ma questo non sta dando l'output desiderato. Non voglio usare pl/sql c'è una funzione di classificazione o una semplice query per ottenere questo. il mio tavolo ha 50 milioni di dischi.

+0

Nel 2012, è possibile utilizzare la funzione 'ROWS'. Nel 2008, deve essere una query più complessa. Per la migliore efficienza, forse un cursore. –

+0

Non c'è alcuna logica nel set di risultati. Perché due ultime righe hanno 'rownumber = 3'? –

+0

@AndreyGordeev 'Rownumber' è in ordine decrescente di 'wdate'. per il cambio di "wstage", "rownumber" dovrebbe incuementare. – Gokul

risposta

4

Supponendo wdate valori sono unici per id, questo potrebbe fare il lavoro:

WITH partitioned AS (
    SELECT 
    *, 
    grp = ROW_NUMBER() OVER (PARTITION BY id   ORDER BY wdate DESC) 
     - ROW_NUMBER() OVER (PARTITION BY id, wstage ORDER BY wdate DESC) 
    FROM atable 
), 
maxdates AS (
    SELECT 
    id, wstage, wstatus, wdate, 
    maxwdate = MAX(wdate) OVER (PARTITION BY id, wstage, grp) 
    FROM partitioned 
) 
SELECT 
    id, wstage, wstatus, wdate, 
    rownumber = DENSE_RANK() OVER (PARTITION BY id ORDER BY maxwdate DESC) 
FROM maxdates 
; 

Il primo CTE determina distinte id, wstage isole, il secondo trova massima wdate per isola, e l'interrogazione principale classifica le righe in base sui valori massimi trovati.

Uno SQL Fiddle demo is available per questa query.

+0

eccellente. abilità eccezionali. Saluti – Gokul