2016-04-07 71 views
0

如何獲取上個月的所有星期一或星期二?我還沒有看到任何關於它的例子。如何獲取上個月的所有星期一或星期二

+0

一些示例(帶cte)'http://bradsruminations.blogspot.ru/search?updated-max = 2011-10-04T12:57:00-07:00&max-results = 1''逐步清晰度'主題 – DimaSUN

+0

你的問題假設一個參考日期。因爲現在在世界不同的地方有不同的日期,「上個月」可能會因不同的人而有所不同。 'GETDATE()'使用服務器的時區。今天有關嗎?如果明天改變呢? –

回答

1
;WITH CTE (X) 
AS 
(
SELECT DATEADD(MM,DATEDIFF(MM,0,GETDATE())-1,0) 
), 
CTE2(N) AS 
(
SELECT 0 
UNION ALL 
SELECT 1+N FROM CTE2 WHERE N< (SELECT DATEDIFF(DD,DATEADD(MM,DATEDIFF(MM,0,GETDATE())-1,0),DATEADD(MM,1,DATEADD(MM,DATEDIFF(MM,0,GETDATE())-1,0))-1)) 
) 
SELECT DATEADD(DD,N,X),DATENAME(DW,DATEADD(DD,N,X)) FROM CTE,CTE2 WHERE DATENAME(DW,DATEADD(DD,N,X)) IN ('Monday','Tuesday') 
+0

感謝您的解決方案。它很整潔。 – angelcake

2

你可以使用:

DECLARE @d DATE = GETDATE(); 

SELECT sub.prev_date 
FROM (SELECT @d, MONTH(DATEADD(MM, -1, @d))) AS s(d,m) 
CROSS APPLY (
    SELECT DATEADD(D, c-1, DATEADD(MM, -1, DATEADD(DD, 1 - DAY(d),d))) AS prev_date 
    FROM (
    VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10), 
      (11),(12),(13),(14),(15),(16),(17),(18),(19),(20), 
      (21),(22),(23),(24),(25),(26),(27),(28),(29),(30),(31))AS x(c) 
    ) AS sub 
WHERE MONTH(sub.prev_date) = s.m 
    AND DATENAME(dw,sub.prev_date) IN ('Monday','Tuesday'); 

LiveDemo

輸出:

╔════════════╗ 
║ prev_date ║ 
╠════════════╣ 
║ 2016-03-01 ║ 
║ 2016-03-07 ║ 
║ 2016-03-08 ║ 
║ 2016-03-14 ║ 
║ 2016-03-15 ║ 
║ 2016-03-21 ║ 
║ 2016-03-22 ║ 
║ 2016-03-28 ║ 
║ 2016-03-29 ║ 
╚════════════╝ 

警告:

SQL Server語言應English其他DATENAME不匹配。

您還可以與DATEPARTweekday進行比較,但您需要知道SET DATEFIRST的設置。


編輯:

短一點:

DECLARE @d DATE = '2015-01-01'; 

SELECT sub.prev_date 
FROM (SELECT DATEADD(DD, c - DAY(@d),DATEADD(MM, -1, @d)) AS prev_date 
     FROM (VALUES (1),(2),(3),(4),(5),(6),(7),(8),(9),(10), 
       (11),(12),(13),(14),(15),(16),(17),(18),(19),(20), 
       (21),(22),(23),(24),(25),(26),(27),(28),(29),(30),(31))AS x(c)) AS sub 
WHERE MONTH(sub.prev_date) = MONTH(DATEADD(MM, -1, @d)) 
    AND DATENAME(dw,sub.prev_date) IN ('Monday','Tuesday'); 

LiveDemo

+1

這樣做非常聰明。非常感謝! – angelcake

2
declare @table table 
(
    ID integer identity, 
    DateRange date, 
    Remark nvarchar(10), 
    MonWeek nvarchar(1), 
    weekgrp integer 
) 

declare @from Date 
declare @newfrom Date 
declare @to Date 
declare @min integer 
declare @max integer 

set @from ='2016-03-01' 
set @to = '2016-03-31' 
set @newfrom = '2016-03-01' 

while @from <= @to 
begin 
    insert into @table (DateRange, Remark) Values (@from,DATENAME(dw,@from)) 

    set @from = DATEADD(dd,1,@from) 
end 

update @table 
set MonWeek = 'Y' 
where Remark = 'Monday' 

select @min = MIN(ID), @max = MAX(ID) from @table 
where MonWeek = 'Y' 

--to calculate week group 
while @min <= @max 
begin 
    Update @table 
    set weekgrp = @min 
    where ID between @min and @min + 7 
    set @min = @min + 7 
end 

select * from @table 
where Remark in ('Monday','Tuesday') 
相關問題