T-SQL查询选择当前,上一周或下周

时间:2013-10-04 19:14:12

标签: sql sql-server-2008 tsql

我相信我的撰写难度很大。

让我们说下面的图像是结果集的一部分。

enter image description here

如果需要,我需要写一个query给出当前工作日(周一至周五)以及前一周和下周工作日(基于前面的一些参数(link button click)端)

所以我们今天说是第4名,所以它会给我30, 1, 2, 3, 4

下面是表格结构。任何改进这种方法的建议都是值得欢迎的。

enter image description here

Gridview中的最终输出将是这样的。

enter image description here

2 个答案:

答案 0 :(得分:3)

以下是我最初解释问题的方法:给我当前周的日期,以及可选的上一周和下周。不管你是否已经有一个满是日期的表(奇怪的是没有DATE列),我的解决方案也是一样的:

-- these are your unmentioned parameters
DECLARE @include_previous_week BIT = 1, @include_next_week BIT = 1;


SET DATEFIRST 1; -- Monday

DECLARE @today DATE = SYSDATETIME();
DECLARE @wd SMALLINT = DATEPART(WEEKDAY, @today);
SET @wd -= CASE WHEN @wd < 6 THEN 0 ELSE 7 END;

;WITH n AS 
(
  SELECT TOP (5) rn = ROW_NUMBER() OVER (ORDER BY [object_id]) 
  FROM sys.all_objects ORDER BY [object_id]
)
SELECT the_date = DATEADD(DAY, rn-@wd, @today) FROM n
UNION ALL 
SELECT DATEADD(DAY, rn-7-@wd, @today) FROM n
WHERE @include_previous_week = 1
UNION ALL 
SELECT DATEADD(DAY, rn+7-@wd, @today) FROM n
WHERE @include_next_week = 1
ORDER BY the_date;

答案 1 :(得分:1)

DECLARE @CurrentDate SMALLDATETIME; -- Or DATE

SET @CurrentDate = '20131004'

SELECT  DATEADD(DAY, (DATEDIFF(DAY, 0, @CurrentDate) / 7) * 7, 0)  AS FirstDayOfTheWeek,
        DATEADD(DAY, (DATEDIFF(DAY, 0, @CurrentDate) / 7) * 7 + 4, 0)  AS LastDayOfTheWeek

结果:

FirstDayOfTheWeek       LastDayOfTheWeek
----------------------- -----------------------
2013-09-30 00:00:00.000 2013-10-04 00:00:00.000

星期一到星期五之间的所有日子:

DECLARE @CurrentDate DATE;
DECLARE @WeekNum SMALLINT;

SET @CurrentDate = '20131004'
SET @WeekNum = +1; -- -1 Previous WK, 0 Current WK, +1 Next WK

SELECT   DATEADD(DAY, dof.DayNum, fdow.FirstDayOfTheWeek) AS DayAsDateTime
FROM    (VALUES (DATEADD(DAY, (DATEDIFF(DAY, 0, @CurrentDate) / 7) * 7 + @WeekNum*7, 0)))  fdow(FirstDayOfTheWeek)
CROSS JOIN (VALUES (0), (1), (2), (3), (4)) dof(DayNum)

/*
DayAsDateTime
-----------------------
2013-10-07 00:00:00.000
2013-10-08 00:00:00.000
2013-10-09 00:00:00.000
2013-10-10 00:00:00.000
2013-10-11 00:00:00.000
*/

SELECT  *
FROM
(
SELECT   DATEADD(DAY, dof.DayNum, fdow.FirstDayOfTheWeek) AS DayAsDateTime, dof.DayNum
FROM    (VALUES (DATEADD(DAY, (DATEDIFF(DAY, 0, @CurrentDate) / 7) * 7 + @WeekNum*7, 0)))  fdow(FirstDayOfTheWeek)
CROSS JOIN (VALUES (0), (1), (2), (3), (4)) dof(DayNum)
) src 
PIVOT( MAX(DayAsDateTime) FOR DayNum IN ([0], [1], [2], [3], [4]) ) pvt

/*
0                       1                       2                       3                       4
----------------------- ----------------------- ----------------------- ----------------------- -----------------------
2013-10-07 00:00:00.000 2013-10-08 00:00:00.000 2013-10-09 00:00:00.000 2013-10-10 00:00:00.000 2013-10-11 00:00:00.000
*/