On the first day of the week, this can be a little complicated, depending on your actual requirements (whether you want to obey the user's date setting or not, use Sunday regardless of the setting, etc.), see this question: Get the first day of the week in SQL Server Here is one way to do this:
DECLARE @today DATE = CURRENT_TIMESTAMP, @y DATE, @m DATE, @w DATE; SELECT @y = DATEADD(YEAR, DATEDIFF(YEAR, 0, @today), 0), @m = DATEADD(MONTH, DATEDIFF(MONTH, 0, @today), 0), @w = DATEADD(DAY, 1-DATEPART(WEEKDAY, @today), @today); SELECT [First day of year] = @y, [First day of month] = @m, [First day of week] = @w;
Whatever you are, you can use in the request, for example. for YTD you would use:
SELECT TicketCount = COUNT(TicketID) FROM dbo.Ticket WHERE DtCheckOut >= @y;
Do not think that you need <part of the request if you are trying to get a counter right now. How many tickets will be checked tomorrow if I launched a request today? If you want to protect yourself from this, you can use:
SELECT COUNT(TicketID) FROM dbo.Ticket WHERE DtCheckOut >= @y AND DtCheckOut < DATEADD(DAY, 1, @now);
You can make it a little more dynamic and pass it into a parameter that says “YTD”, “MTD” or “WTD”, for example
CREATE PROCEDURE dbo.CountTickets @Range CHAR(3) = 'YTD' AS BEGIN SET NOCOUNT ON; -- you may want to handle invalid ranges, eg IF @Range NOT IN ('YTD', 'MTD', 'WTD') BEGIN RAISERROR('Please enter a valid range.', 11, 1); RETURN; END DECLARE @today DATE = CURRENT_TIMESTAMP, @start DATE; SELECT @start = CASE @range WHEN 'YTD' THEN DATEADD(YEAR, DATEDIFF(YEAR, 0, @today), 0) WHEN 'MTD' THEN DATEADD(MONTH, DATEDIFF(MONTH, 0, @today), 0) WHEN 'WTD' THEN DATEADD(DAY, 1-DATEPART(WEEKDAY, @today), @today) END; SELECT Range = @range, TicketCount = COUNT(TicketID) FROM dbo.Ticket WHERE dtCheckOUt >= @start; END GO