February 16, 2012 at 2:23 pm
Hello. Given a list of SiteId/date combinations and a date tally table I'm trying to figure out what dates in 2012 that sites are missing data for.
CREATE TABLE #AllDates(SiteDate smalldatetime)
INSERT #AllDates
SELECT '1/1/12' union
SELECT '1/2/12' union
SELECT '1/3/12' union
SELECT '1/4/12'
etc...
CREATE TABLE #SitesAndDates(SiteId int, SiteDate smalldatetime)
INSERT #SitesAndDates
SELECT 1, '1/1/12' UNION
SELECT 1, '1/3/12' UNION
SELECT 1, '1/4/12' UNION
SELECT 2, '1/2/12' UNION
SELECT 2, '1/3/12' UNION
SELECT 2, '1/4/12'
etc...
The result here would be that Site 1 didn't report 1/2 and Site 2 missing 1/1. Obviously can't just left join #Alldates to #SitesAndDates on SiteDate. I did it a different way using row_number() but felt like I was cheating 😀
Ken
February 16, 2012 at 2:27 pm
you need to be able to also join against a master list of all sites.
when you cross join dates and sites, you get all possible values...which you can then join to teh list of data and find the missing items.
then it's a lit easier:
SELECT *
FROM #AllDates
CROSS JOIN #AllSites
LEFT OUTER JOIN #SitesAndDates
ON #AllDates.AllDates = #SitesAndDates.SiteDate
AND #AllSites.SiteId =#SitesAndDates.SiteId
WHERE #SitesAndDates.SiteID IS NULL
Lowell
February 16, 2012 at 3:03 pm
Thanks Lowell. That Cross Join is helpful.
Ken
Viewing 3 posts - 1 through 2 (of 2 total)
You must be logged in to reply to this topic. Login to reply