-1

我相信我有一个很难编写的查询。

可以说下图是结果集的一部分。

在此处输入图像描述

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

所以让我们说今天是第四天,所以它会返回给我30, 1, 2, 3, 4

下面是表结构。欢迎提出任何改进此方法的建议。

在此处输入图像描述

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

在此处输入图像描述

4

2 回答 2

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;
于 2013-10-04T19:40:07.283 回答
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
*/
于 2013-10-04T19:38:08.957 回答