Du kan bruge en Tally Table
for at generere alle kombinationer af Date
og Unit
. Når du har fået alle kombinationerne, kan du bruge NOT EXISTS
for at få de manglende data.
DECLARE @minDate AS DATE
DECLARE @maxDate AS DATE
SELECT
@minDate = MIN([Date]),
@maxDate = MAX([Date])
FROM TestData
;WITH E1(N) AS(
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL
SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
),
E2(N) AS(SELECT 1 FROM E1 a CROSS JOIN E1 b),
E4(N) AS(SELECT 1 FROM E2 a CROSS JOIN E2 b),
Tally(N) AS(
SELECT TOP(DATEDIFF(DAY, @minDate, @maxDate) + 1)
ROW_NUMBER() OVER(ORDER BY(SELECT NULL))
FROM E4
),
CteDatesAndUnits([Date], Unit) AS(
SELECT
DATEADD(DAY, t.N - 1, @minDate),
u.Unit
FROM Tally t
CROSS JOIN (
SELECT DISTINCT Unit FROM TestData
)u
)
SELECT *
FROM CteDatesAndUnits c
WHERE NOT EXISTS(
SELECT *
FROM TestData
WHERE
[Date] = c.[Date]
AND Unit = c.Unit
)
Resultat
| Date | Unit |
|------------|--------|
| 2012-01-01 | Unit B |
| 2012-01-02 | Unit A |
| 2012-01-02 | Unit B |
Siden Unit
vil altid være Unit A
og Unit B
, kan du erstatte denne linje:
SELECT DISTINCT Unit FROM TestData
med denne:
SELECT 'Unit A' AS Unit UNION ALL SELECT 'Unit B'