简体   繁体   English

基于星期几的SQL自动选择日期范围

[英]SQL autoselecting date range based on today's day of the week

--This is using SQL -这是使用SQL

I Have tried and failed at this a few times, 我已经尝试过几次但失败了,

I have a sales table with an order date in the following format '2014-05-15 00:00:00.000' 我有一个销售表,订单日期的格式为“ 2014-05-15 00:00:00.000”

I would like to have a report that runs on the basis that if @today is less than Friday, show last weeks date range, if @today is Saturday or Sunday, then use this weeks date range 我想生成一个报告,其依据是,如果@today小于星期五,则显示上周的日期范围,如果@today是周六或周日,则使用该周的日期范围

assuming I only want to see the fields SalesOrder and OrderDate 假设我只想查看字段SalesOrder和OrderDate

Thanks in advance, 提前致谢,

Dean 院长

Tweak to your hearts content (running this in SQL Server Management Studio will display messages with the correct outputs). 调整您的内心内容(在SQL Server Management Studio中运行此内容将显示具有正确输出的消息)。 Use the variables to filter your SELECT statement and remove the PRINT operators: 使用变量过滤您的SELECT语句并删除PRINT运算符:

DECLARE @ReportDate DATETIME
DECLARE @StartOfWeek DATETIME
DECLARE @DayOfWeek INT 

SET @ReportDate = '2014-05-15 00:00:00.000' --This will be your variable in report builder
SET @DayOfWeek = DATEPART(dw,@ReportDate)

/* 
Take away the day of the week from the report date to
get the beginning of that week.
*/

--Adjust the +1 to mark the start of your week (ie. +2 makes Monday the start)
SET @StartOfWeek = DATEADD(dd, (-(@DayOfWeek) + 1), @Reportdate)

--Now do stuff based on the report date (set the beginning of the week)
IF @DayOfWeek BETWEEN 2 AND 5 --Friday is day 6 (Sunday is first day in SQL and the BETWEEN clause is inclusive)
BEGIN
    PRINT 'Monday to Thursday' --This line can be removed
    /* Now minus 7 to get the beginning of the previous week */
    SET @StartOfWeek = DATEADD(dd, -7, @StartOfWeek)
END
---------------------------------------------------
/*
This entire box is optional (can be removed) but just for demonstration purposes to
show that the date stuff works
*/

IF @DayOfWeek = 6 --Friday is day 6 
BEGIN
    PRINT 'Friday'
END
IF @DayOfWeek IN (7,1) --Saturday day 7, Sunday day 1
BEGIN
    PRINT 'Saturday or Sunday'
END
---------------------------------------------------

--This is where your SELECT statement goes (instead of PRINT operators below)
PRINT 'StartOfWeek = ' + CAST(@StartOfWeek AS NVARCHAR(255))
PRINT 'EndOfWeek = ' + CAST(DATEADD(dd,7,@StartOfWeek) AS NVARCHAR(255))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM