T-SQL日期工作日日期范围

时间:2016-06-27 13:39:25

标签: tsql

我有一个简单的查询来返回两列:

DECLARE @Test TABLE 
(
    Product VARCHAR(100)

    )

INSERT INTO @Test VALUES ('Hats')
INSERT INTO @Test VALUES ('Hats')
INSERT INTO @Test VALUES ('Hats')
INSERT INTO @Test VALUES ('Hats')
INSERT INTO @Test VALUES ('Shirts')
INSERT INTO @Test VALUES ('Shirts')
INSERT INTO @Test VALUES ('Trousers')
INSERT INTO @Test VALUES ('Trousers')
INSERT INTO @Test VALUES ('Trousers')
INSERT INTO @Test VALUES ('Trousers')
INSERT INTO @Test VALUES ('Trousers')
INSERT INTO @Test VALUES ('Shoes')

SELECT  Product 
        ,COUNT(1) AS Total
        FROM @Test
GROUP BY Product

我需要在不同年份的星期一到星期五之间输入我的WHERE子句日期范围,发现这个有点棘手。

即 周一至周五

2016
06.06.16 - 10.06.16
13.06.16 - 17.06.16

2015
03.08.15 - 07.08.15
10.08.15 - 14.08.15

2 个答案:

答案 0 :(得分:0)

试试这个

DECLARE @CurrentDate DATETIME = '2016.06.23'

DECLARE @CurrentMonday DATETIME = DATEADD(wk, DATEDIFF(wk,0,@CurrentDate), 0) -- 2016.06.20 MONDAY
DECLARE @CurrentFriday DATETIME = DATEADD(dd, 4, @CurrentMonday) -- 2016.06.24 FRIDAY

然后你可以在where子句中使用currentMonday和currentFriday。

E.g。

SELECT
     *
FROM
     YourTable
WHERE
    date >= @CurrentMonday AND
    date <= @CurrentFriday 

答案 1 :(得分:0)

DECLARE @Test TABLE 
(
    Product VARCHAR(100)
    ,DateRange Date

    )

INSERT INTO @Test VALUES ('Hats', '20160610')
INSERT INTO @Test VALUES ('Hats','20160612')
INSERT INTO @Test VALUES ('Hats','20150804')
INSERT INTO @Test VALUES ('Hats','20150804')
INSERT INTO @Test VALUES ('Shirts','20150813')
INSERT INTO @Test VALUES ('Shirts','20150825')
INSERT INTO @Test VALUES ('Trousers','20150819')
INSERT INTO @Test VALUES ('Trousers','20150827')
INSERT INTO @Test VALUES ('Trousers','20150607')
INSERT INTO @Test VALUES ('Trousers','20150611')
INSERT INTO @Test VALUES ('Trousers','20150808')
INSERT INTO @Test VALUES ('Shoes','20150809')




SELECT
    Product
     ,SUM(CASE WHEN DateRange BETWEEN '20150803' AND '20150807' THEN 1 ELSE 0 END) AS '03.08.15 – 07.08.15'
     ,SUM(CASE WHEN DateRange BETWEEN '20150810' AND '20150814' THEN 1 ELSE 0 END) AS '10.08.15 – 14.08.15'
     ,SUM(CASE WHEN DateRange BETWEEN '20160606' AND '20160610' THEN 1 ELSE 0 END) AS '06.06.16 – 10.06.16'
    ,SUM(CASE WHEN DateRange BETWEEN '20160613' AND '20160617' THEN 1 ELSE 0 END) AS '13.06.16 – 17.06.16'
FROM
     @Test
WHERE  Product IN (
        'Hats'
        ,'Shirts'
        ,'Trousers'
        ,'Shoes'
                ) 
GROUP BY Product
 ORDER BY Product ASC