Sorry about the vague subject but I couldn’t think what to put.
Here’s my problem, I’m doing a query on a table that returns me a count of items related to a day. I want to make sure that if I do a query on the DB, I always get a set number of rows. For example, imagine I have the following table that contains a log of when people log into a website:
**WebsiteLogin** id: Integer login_date: Datetime
I can then get counts of the logins for each date by doing something like:
SELECT DATE(login_date), COUNT(*) FROM WebsiteLogin GROUP BY DATE(login_date)
Which works great and will return me the data I want. But imagine my website was quite unpopular on the weekends. The data returned would look like:
2008-12-10, 100 2008-12-11, 124 2008-12-12, 151 2008-12-15, 141 2008-12-16, 111
The 13th & 14th are missing because there was no data for those dates. Is there any way I can change my query so that I get data that includes all the dates I query on. E.g.
2008-12-10, 100 2008-12-11, 124 2008-12-12, 151 2008-12-13, 0 2008-12-14, 0 2008-12-15, 141 2008-12-16, 111
I imagine I could do this if I set up a table containing all the dates in a year and then using a left/right join but that’s really messy way of doing it.
So any clues on a nice way to do this in SQL? Or is programmatically my only choice? Cheers for any input.
Nope. That’s pretty much how to do it. On the other hand, you can use a temporary table and populate it with just the date range required.
If only MS SQL had virtual tables, where you provided a generator function…