U kunt een Tally Table
gebruiken om alle combinaties van Date
. te genereren en Unit
. Nadat je alle combinaties hebt gevonden, kun je NOT EXISTS
. gebruiken om de ontbrekende gegevens te krijgen.
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
)
Resultaat
| Date | Unit |
|------------|--------|
| 2012-01-01 | Unit B |
| 2012-01-02 | Unit A |
| 2012-01-02 | Unit B |
Sinds de Unit
is altijd Unit A
en Unit B
, kunt u deze regel vervangen:
SELECT DISTINCT Unit FROM TestData
hiermee:
SELECT 'Unit A' AS Unit UNION ALL SELECT 'Unit B'