2015-12-28 118 views
1

我想從今天開始獲得最後8周(GETDATE()) 因此,所有8周的格式必須爲dd/mm。 我想是這樣的獲取最近x個日曆周的第一天和第一天

select "start_of_week" = cast(datepart(dd,dateadd(week, datediff(week, 0, getdate()), 0)) as CHAR(2))+'/'+cast(datepart(mm,dateadd(week, datediff(week, 0, getdate()), 0)) as CHAR(2)); 

,這是很好的只對當前星期,但如何將這個查詢並返回CURR-1,CURR-2,... CURR-7周。最終的結果必須是表與一個玩家一些量和格式爲dd /毫米

+0

不清楚........ –

+0

我剛剛訪問過您的個人資料,發現您很少接受和/或投票答覆。因此,請允許我提示一個提示:請注意,所有在SO上給出答案的專業人員都渴望獲得聲望點。請閱讀[this:someone-answers](http://stackoverflow.com/help/someone-answers)。也可以看看你的老問題。謝謝! – Shnugo

回答

0

在這裏你去:

DECLARE @DateTable TABLE (ADate DATETIME) 
DECLARE @CurrentDate DATETIME 

SET @CurrentDate = GETDATE() 

WHILE (SELECT COUNT(*) FROM @DateTable WHERE DATEPART(dw, ADate) = 2) <= 7 
BEGIN 
INSERT INTO @DateTable 
SELECT @CurrentDate 

SET @CurrentDate = DATEADD(dd, -1, @CurrentDate) 

END 

SELECT "start_of_week" = cast(datepart(dd,dateadd(week, datediff(week, 0, ADate), 0)) as CHAR(2)) 
         +'/'+cast(datepart(mm,dateadd(week, datediff(week, 0, ADate), 0)) as CHAR(2)) 
FROM @DateTable 
WHERE DATEPART(dw, ADate) = 2 

DELETE @DateTable 

輸出

start_of_week 
28/12 
21/12 
14/12 
7 /12 
30/11 
23/11 
16/11 
9 /11 
+0

恭喜你,你已經接受了......但我必須承認,在我看來,這個解決方案非常糟糕:不需要循環,文化依賴,RBAR,醜陋的日期格式......但是:抱歉和快樂的編碼! – Shnugo

0

語法每週: 選擇「start_of_week」 = 鑄造(日期部分(DD,DATEADD(周,DATEDIFF(周,0,GETDATE ()) - X,0))爲CHAR(2))

select "start_of_week" = 
    cast(datepart(dd,dateadd(week, datediff(week, 0, getdate()) - 0, 0)) as CHAR(2)) , 
"previous_week1" = 
    +'/'+cast(datepart(mm,dateadd(week, datediff(week, 0, getdate()) - 1, 0)) as CHAR(2)), 
"previous_week2" = 
    +'/'+cast(datepart(mm,dateadd(week, datediff(week, 0, getdate()) - 2, 0)) as CHAR(2)), 
"previous_week3" = 
    +'/'+cast(datepart(mm,dateadd(week, datediff(week, 0, getdate()) - 3, 0)) as CHAR(2)); 

等....謝謝

+0

你真的嘗試過嗎?如果你想讓它們「並排」,那麼'convert(varchar(5),getdate() - 7/*設置爲14,21等等* /,103)'... – Shnugo

1

也許一樣容易呢?

WITH EightNumbers(Nmbr) AS 
(
      SELECT 0 
    UNION SELECT -1 
    UNION SELECT -2 
    UNION SELECT -3 
    UNION SELECT -4 
    UNION SELECT -5 
    UNION SELECT -6 
    UNION SELECT -7 
    UNION SELECT -8 
) 
SELECT CONVERT(VARCHAR(5),GETDATE()+(Nmbr*7),103) 
FROM EightNumbers 
ORDER BY Nmbr DESC 

如果您需要(如標題所暗示的)一週的「第一天」,你可能會改變選擇到:

SELECT CONVERT(VARCHAR(5),GETDATE()+(Nmbr*7)-DATEPART(dw,GETDATE())[email protected]@DATEFIRST,103) 
FROM EightNumbers 
ORDER BY Nmbr DESC 

請注意,「一週的第一天」依賴在你係統的文化上。看看@@DATEFIRST

結果:

28/12 
21/12 
14/12 
07/12 
30/11 
23/11 
16/11 
09/11 
02/11 
0

假設sys.all_objects至少有8行,你想的第一天(你沒有在你的問題中指定:

select top 8 convert(varchar(5), 
     dateadd(WEEK, 
       1-1* ROW_NUMBER() over(order by newid()), 
       dateadd(DD, 
          1-datepart(dw,getdate()), 
          getdate())), 
     1) as [FirstDayOfWeek] 
    from sys.all_objects 

轉換隻是給出月/日。行號用於給出數字1-8。我將行號乘以-1,並加1以獲得數字0,-1,-2,... -7,並將日期添加到本週的第一天。我發現本週的第一天通過使用getdate和日期添加了本週的日子的負數版本+1。

相關問題