2012-03-08 170 views
0

我有以下的sql語句來查找所有星期一的日期。sql查找今天日期之後的所有星期一

SELECT DateAdd(week, 
        o1.v + o0.v, 
        DateAdd(day, 
          2 - DatePart(dw, Convert(VARCHAR(4), 2012) + '-01-01'), 
          Convert(VARCHAR(4), 2012) + '-01-01' 
         ) 
       ) 
     FROM (SELECT 0 AS v UNION 
      SELECT 8 UNION 
      SELECT 16 UNION 
      SELECT 24 UNION 
      SELECT 32 UNION 
      SELECT 40 UNION 
      SELECT 48) AS o1 
CROSS JOIN (SELECT 0 AS v UNION 
      SELECT 1 UNION 
      SELECT 2 UNION 
      SELECT 3 UNION 
      SELECT 4 UNION 
      SELECT 5 UNION 
      SELECT 6 UNION 
      SELECT 7) AS o0 
    WHERE 2012 = DatePart(year, 
          DateAdd(week, 
            o1.v + o0.v, 
            DateAdd(day, 
              2 - DatePart(dw, Convert(VARCHAR(4), 2012) + '-01-01'), 
              Convert(VARCHAR(4), 2012) + '-01-01') 
           ) 
         ) 

我該如何修改它才能在今天的日期之後找到所有星期一的日期?

回答

0

你可以在那裏做但我認爲它很複雜。 的CTE是一個很好的解決方法:

with DAYS as (
    SELECT DateAdd(week, o1.v + o0.v, DateAdd(day, 2 - DatePart(dw 
, Convert(VARCHAR(4), 2012) + '-01-01'), Convert(VARCHAR(4) 
, 2012) + '-01-01')) as MY_DAY 
    FROM (SELECT 0 AS v UNION SELECT 8 UNION SELECT 16 UNION SELECT 24 
     UNION SELECT 32 UNION SELECT 40 UNION SELECT 48) AS o1 
    CROSS JOIN (SELECT 0 AS v UNION SELECT 1 UNION SELECT 2 UNION SELECT 3 
     UNION SELECT 4 UNION SELECT 5 UNION SELECT 6 UNION SELECT 7) AS o0 
    WHERE 2012 = DatePart(year, DateAdd(week, o1.v + o0.v, DateAdd(day 
,  2 - DatePart(dw, Convert(VARCHAR(4), 2012) + '-01-01') 
,  Convert(VARCHAR(4), 2012) + '-01-01'))) 
) 
select MY_DAY from DAYS 
where MY_DAY >getdate() 
3

我會創造一個calendar table而不是寫一個複雜的查詢。然後,你可以寫這樣的清晰,簡單的查詢:

select 
    c.BaseDate 
from 
    dbo.Calendar c 
where 
    c.DayOfWeek = 'Monday' and 
    c.YearNumber = year(getdate()) and 
    c.BaseDate > getdate() 

作爲一般規則,日曆表是使用日期,因爲它是很多簡單的查詢和維護比功能最簡單的解決方案,您可以在需要支持新的日期屬性時添加列。

+0

的最好的事情有關日曆表是查詢他們可以看到* *是正確的。將此查詢與SQL Server或Oracle中的一個使用日期算法進行比較。在一個日曆表中的百年只有36k行,這實際上什麼都沒有。 – 2012-03-08 11:04:27

1

有許多功能可以幫助長時間使用CTE,它會很簡單,下面有一些建議,希望對它有所幫助。

declare @DateFrom Date 
declare @DateTo Date 

set @DateFrom ='2016-01-01' 
set @DateTo = '2016-12-31' 

SELECT AllDates as MonDates from 
(Select DATEADD(d, number, @dateFrom) as AllDates from master..spt_values 
    where type = 'p' and number between 0 and datediff(dd, @dateFrom, @dateTo)) AS D1  
WHERE DATENAME(dw, D1.AllDates)In('Monday') 
0

我成功地使用這個查詢(我適應的答案here之一)

SELECT MondaysThisMonth = cast (DATEADD(DAY,n,MondayBeforeFOM) as date) 
FROM (
    SELECT FirstOfMonth, MondayBeforeFOM = DATEADD(DAY,DATEDIFF(DAY,0,FirstOfMonth)/7*7,0) 
    FROM (SELECT FirstOfMonth = DATEADD(MONTH,DATEDIFF(MONTH,0,GETDATE()),0)) d 
) e 
CROSS JOIN (SELECT 7 UNION ALL SELECT 14 UNION ALL SELECT 21 UNION ALL SELECT 28 UNION ALL SELECT 35) f (n) 
WHERE DATEADD(DAY,n,MondayBeforeFOM) < DATEADD(MONTH,1,FirstOfMonth) 
相關問題