Dette er en 3-trins proces, rangord først dine registreringer for hver konto/målerkombination ved hjælp af ROW_NUMBER()
SELECT *,
RowNumber = ROW_NUMBER() OVER(PARTITION BY AccountNumber, MeterNumber
ORDER BY EndDate DESC)
FROM Meter
OUTPUT
Kontonummer | MeterNumber | Startdato | Slutdato | RateCode | Rækkenummer |
---|---|---|---|---|---|
0142628117 | 123470203 | 2020-04-22 | 9999-12-31 | ETF0_APR20 | 1 |
0142628117 | 123470203 | 2019-04-10 | 2020-04-09 | ***Tilpasset*** | 2 |
0142628117 | 123470205 | 2020-04-22 | 9999-12-31 | ETF0_APR20 | 1 |
0142628117 | 123470205 | 2019-04-10 | 2020-04-09 | ***Tilpasset*** | 2 |
1363445 | 105238304 | 2018-10-02 | 2019-08-11 | ***Tilpasset*** | 1 |
1363445 | 105238304 | 2016-02-25 | 2016-04-22 | ***Tilpasset*** | 2 |
1363445 | 130359929 | 2019-08-12 | 9999-12-31 | ***Tilpasset*** | 1 |
N.B. Nogle data forkortet for at blive vist bedre
Derefter kan du filtrere efter var RowNumber =1 for at få den seneste slutdato for hver måler.
Dernæst skal du tælle de forskellige Slutdato/RateCode-kombinationer, du kan ikke bruge COUNT(DISTINCT ...)
i en vinduesfunktion, men du kan efterligne dette ved at bruge DENSE_RANK()
:
SELECT *,
CntDistinct = DENSE_RANK() OVER(PARTITION BY AccountNumber
ORDER BY EndDate, RateCode)
+ DENSE_RANK() OVER(PARTITION BY AccountNumber
ORDER BY EndDate DESC, RateCode DESC) - 1
FROM ( SELECT *,
RowNumber = ROW_NUMBER() OVER(PARTITION BY AccountNumber, MeterNumber
ORDER BY EndDate DESC)
FROM Meter AS m
) AS m
WHERE m.RowNumber = 1;
OUTPUT
Kontonummer | MeterNumber | Startdato | Slutdato | RateCode | CntDistinct |
---|---|---|---|---|---|
0142628117 | 123470203 | 2020-04-22 | 9999-12-31 | ETF0_APR20 | 1 |
0142628117 | 123470205 | 2020-04-22 | 9999-12-31 | ETF0_APR20 | 1 |
1363445 | 130359929 | 2019-08-12 | 9999-12-31 | ***Tilpasset*** | 2 |
1363445 | 105238304 | 2018-10-02 | 2019-08-11 | ***Tilpasset*** | 2 |
N.B. Nogle data forkortet for at blive vist bedre
Læg endelig alt dette ind i en yderligere underforespørgsel og begræns til, hvor der er mere end én unik kombination af EndDate/RateCode:
SELECT AccountNumber, MeterNumber, StartDate, EndDate, RateCode
FROM ( SELECT *,
CntDistinct = DENSE_RANK() OVER(PARTITION BY AccountNumber
ORDER BY EndDate, RateCode)
+ DENSE_RANK() OVER(PARTITION BY AccountNumber
ORDER BY EndDate DESC, RateCode DESC) - 1
FROM ( SELECT *,
RowNumber = ROW_NUMBER() OVER(PARTITION BY AccountNumber, MeterNumber
ORDER BY EndDate DESC)
FROM Meter AS m
) AS m
WHERE m.RowNumber = 1
) AS m
WHERE m.CntDistinct > 1;
OUTPUT
Kontonummer | MeterNumber | Startdato | Slutdato | RateCode |
---|---|---|---|---|
0500000178767001363445 | TCA105238304 | 2018-10-02 | 2019-08-11 | ***Tilpasset*** |
0500000178767001363445 | TCA130359929 | 2019-08-12 | 9999-12-31 | ***Tilpasset*** |