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

SQL Server 2005:raggruppamento di valori, visualizza solo le modifiche

Userei un'espressione di tabella comune per includere un numero di riga sequenziale basato su date_loaded, quindi lo userei in un self-join, come segue:

CREATE TABLE #temp (
    value INT,
    date_loaded DATETIME
)

INSERT INTO #temp VALUES (1,'2012-03-7')
INSERT INTO #temp VALUES (1,'2012-03-6')
INSERT INTO #temp VALUES (1,'2012-03-5')
INSERT INTO #temp VALUES (3,'2012-03-4')
INSERT INTO #temp VALUES (4,'2012-03-3')
INSERT INTO #temp VALUES (1,'2012-03-2')

;WITH cte AS (SELECT ROW_NUMBER() OVER (ORDER BY date_loaded) AS n, value, date_loaded FROM #temp)
SELECT t2.value, t2.date_loaded
FROM cte t2 LEFT JOIN cte t1 ON t2.n = t1.n + 1
WHERE t2.value <> ISNULL(t1.value, -1)

DROP TABLE #temp