Given these tables
table Channel
--------------
ChannelID int IDENTITY
<other irrelevant stuff>
table Program
--------------
ProgramID int IDENTITY
ChannelID int
AiringDate datetime
<other irrelevant stuff>
and this query
SELECT C.ChannelID, t.AiringDate
FROM
Channel C
LEFT JOIN (
SELECT distinct ChannelID
FROM Program
WHERE AiringDate = '2010-01-16'
) p
ON p.ChannelID=C.ChannelID
CROSS JOIN (
SELECT AiringDate = '2010-01-16'
) t
WHERE C.ChannelID IN (1, 2, 74, 15, 906) /* the Channel table contains more channels than we are interested in */
AND p.ChannelID IS NULL
which yields
ChannelID | AiringDate
----------|-----------
2 | 2010-01-16
906 | 2010-01-16
how can I modify it to accept a date range, so that the result will be something like
ChannelID | AiringDate
----------|-----------
2 | 2010-01-16
906 | 2010-01-16
2 | 2010-01-17
906 | 2010-01-17
if there were no programs aired on these 2 channels any of these two days
This returns no rows
SELECT C.ChannelID, t.AiringDate
FROM
Channel C
LEFT JOIN (
SELECT distinct ChannelID, AiringDate
FROM Program
WHERE AiringDate between '2010-01-16' and '2010-01-17'
) p
ON p.ChannelID=C.ChannelID
CROSS JOIN (
SELECT AiringDate = '2010-01-16'
union
SELECT AiringDate = '2010-01-17'
) t
WHERE C.ChannelID IN (1, 2, 74, 15, 906)
AND p.ChannelID IS NULL
That CROSS JOIN
is a bit ugly, and it would be nice to get rid of it altogether. Note that the first example query is a bit convoluted; For single dates I have a simpler one that only outputs missing ChannelIDs:
SELECT C.ChannelID
FROM
Channel C
LEFT JOIN (
SELECT distinct ChannelID
FROM Program
WHERE AiringDate = '2010-01-16'
) p
ON p.ChannelID=C.ChannelID
WHERE C.ChannelID IN (1, 2, 74, 15, 906)
AND p.ChannelID IS NULL