Anda dapat menggunakan Tabel Penghitungan
untuk menghasilkan semua kombinasi Date
dan Unit
. Setelah Anda mendapatkan semua kombinasi, Anda dapat menggunakan NOT EXISTS
untuk mendapatkan data yang hilang.
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
)
Hasil
| Date | Unit |
|------------|--------|
| 2012-01-01 | Unit B |
| 2012-01-02 | Unit A |
| 2012-01-02 | Unit B |
Sejak Unit
akan selalu Unit A
dan Unit B
, Anda dapat mengganti baris ini:
SELECT DISTINCT Unit FROM TestData
dengan ini:
SELECT 'Unit A' AS Unit UNION ALL SELECT 'Unit B'