Sqlserver
 sql >> Database >  >> RDS >> Sqlserver

Raggruppare i dati in base alla modifica del valore della colonna di raggruppamento in ordine

Esiste una tecnica (più o meno) nota per risolvere questo tipo di problema, che coinvolge due ROW_NUMBER() chiamate, in questo modo:

WITH marked AS (
  SELECT
    *,
    grp = ROW_NUMBER() OVER (PARTITION BY product        ORDER BY date)
        - ROW_NUMBER() OVER (PARTITION BY product, price ORDER BY date)
  FROM #ph
)
SELECT
  product,
  date_from = MIN(date),
  date_to   = MAX(date),
  price
FROM marked
GROUP BY
  product,
  price,
  grp
ORDER BY
  product,
  MIN(date)

Uscita:

product  date_from   date_to        price 
-------  ----------  -------------  ----- 
1        2012-01-01  2012-01-04     1     
1        2012-01-05  2012-01-08     2     
1        2012-01-09  2012-01-12     1