Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query for YTD, MTD, WTD totals

I would like this query to be able to automagically know today's date & time as well as the first of the year (or month) (or week)...

SELECT TicketID
FROM   Ticket
WHERE     (Ticket.DtCheckOut > '1/1/2011 12:00:00 AM') 
      AND (Ticket.DtCheckOut < '8/27/2011 12:00:00 AM')

I know it will use GETDATE() in some form, but you don't want to see what I've come up with, I promise!

Here is what I was reading on GETDATE() MDSN: GETDATE(Transact-SQL)

I looked around here and Google - and didn't find anything 'clean' - so any input would be awesome!

like image 799
Fuginator Avatar asked Aug 26 '11 23:08

Fuginator


1 Answers

DECLARE @now DATETIME
SET @now = GETDATE()

SELECT
    DATEADD(yy, DATEDIFF(yy, 0, @now), 0) AS FirstDayOfYear,
    DATEADD(mm, DATEDIFF(mm, 0, @now), 0) AS FirstDayOfMonth,
    DATEADD(DAY, -DATEDIFF(dd, @@DATEFIRST - 1, @now) % 7, @now) AS FirstDayOfWeek

@@DATEFIRST is SQL Server's first day of the week, which defaults to Sunday if you are using U.S. English.

like image 72
NullUserException Avatar answered Oct 10 '22 01:10

NullUserException