Sqlserver
 SQL >> Database >  >> RDS >> Sqlserver

Colmare i buchi temporali e trascinare l'ultimo valore non nullo in SQL

Ho preparato una SQL Fiddle così puoi giocare con questa soluzione.

L'idea è costruire una tabella di lavoro @Months, farne il cross join con ogni anno presente nei tuoi dati e generare così un elenco completo di mesi per tutti gli anni. Poi faccio il left join dei tuoi dati di esempio (la tabella chiamata TEST; vedi la fiddle per lo schema) su quell'elenco, così i mesi che hanno valori li mantengono. La sfida restante era trascinare in avanti il valore del mese più recente quando il mese corrente è vuoto. Per questo ho usato una sottoquery correlata che riunisce i valori su se stessi, corrispondendo solo alla riga con il rank più alto che ha un valore non nullo. Ciò produce l'intero result set.

Se vuoi limitare l'output a un anno o mese specifico, basta aggiungere una clausola WHERE appena prima dell'ORDER BY finale.

Buon divertimento!

Schema di test

CREATE TABLE TEST( Month tinyint, Year int, Value int) INSERT INTO TEST(Month, Year, Value) VALUES (1,2013,100), (4,2013,101), (8,2013,102), (2,2014,103), (4,2014,104)

Query

DECLARE @Months Table(Month tinyint) Insert into @Months(Month) Values (1),(2),(3),(4),(5),(6),(7),(8),(9),(10),(11),(12); With tblValues as ( select Rank() Over (ORDER BY y.Year, m.Month) as [Rank], m.Month, y.Year, t.Value from @Months m CROSS JOIN ( Select Distinct Year from Test ) y LEFT JOIN Test t on t.Month = m.Month and t.Year = y.Year ) Select t.Month, t.Year, COALESCE(t.Value, t1.Value) as Value from tblValues t left join tblValues t1 on t1.Rank = ( Select Max(tmax.Rank) From tblValues tmax Where tmax.Rank < t.Rank AND tmax.Value is not null ) Order by t.Year, t.Month