根據您的實際需求(無論您是否遵守用戶的日期優先設置,使用星期日而不考慮設置等),對於每週的第一天,可能會有點棘手,請參閱此問題:Get first day of week in SQL Server。這裏有一種方法:
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;
無論你在哪一個人之後,你都可以在查詢中使用,例如,爲YTD你可以使用:
SELECT TicketCount = COUNT(TicketID)
FROM dbo.Ticket
WHERE DtCheckOut >= @y;
真的不認爲你需要查詢的<部分,如果你想獲得數到現在。如果我今天正在運行查詢,明天將簽出多少張門票?如果你想保護自己免受您可以使用:
SELECT COUNT(TicketID)
FROM dbo.Ticket
WHERE DtCheckOut >= @y
AND DtCheckOut < DATEADD(DAY, 1, @now);
你可以讓它多了幾分活力和傳遞,上面寫着「YTD」,「MTD」或「WTD」,例如參數
CREATE PROCEDURE dbo.CountTickets
@Range CHAR(3) = 'YTD'
AS
BEGIN
SET NOCOUNT ON;
-- you may want to handle invalid ranges, e.g.
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
你想在同一個查詢中的所有三個總數?對你而言,第一天是什麼意思? –
對不起 - 沒有三個不同的查詢,所有類似的目標...星期一(爲此)是星期天。 – Fuginator
呵呵,並且更加清楚,我想COUNT()TicketID列... – Fuginator