SQL DateDiff, Between, and GetDate()
Posted by Stephen Weyrick | Tags: sql
Today I was trying to fix problem with a report that sums up hours, and I had a huge brain fart. What took me an hour to fix, should have only taken me about 5 minutes. I thought that it would make a good blog post, because I really don't want to make this same stupid mistake again.
The problem involved trying to sum up hours by date, using the built in SQL function getdate(). Below is the query that I was running.
SELECT SUM(personnelNumber) as TotalHours, CONVERT(VARCHAR(10), dateTime, 101) as Date
FROM tblReturnTotals
WHERE dateTime
BETWEEN getdate()-7 AND getdate()-1
AND location = '5'
GROUP BY CONVERT(VARCHAR(10), DateTime, 101)
Because getdate() grabs the hour along with the date, the query wouldn't sum the hours from the previous day in the date range. For instance, if the time is 9 AM right now, then the date range ends yesterday at 9 AM. Whoops!!! Below is a quick fix using dateDiff().
SELECT SUM(personnelNumber) as TotalHours, CONVERT(VARCHAR(10), dateTime, 101) as Date
FROM tblReturnTotals
WHERE datediff(dd,datetime, getdate()) < 7 AND
datediff(dd,datetime, getdate()) >= 1
AND location = '5'
GROUP BY CONVERT(VARCHAR(10), DateTime, 101)
5 responses so far ↓
Leave a Comment