2016-04-28 96 views
1

我一直在尋找檔案但沒有找到我正在尋找的內容 - 我很樂意提供一些指導。將iso_week轉換爲SQL中的日曆日期

我有一個數據集,我想報告供應商(STAFFID)和工作周的約會總數,後一週是週一的日期。我和datepart(iso_week, appointment_date) as week_of_yr一起玩,這讓我成爲那裏的一部分 - 我可以按周分組以獲得正確的數字。然而,我無法弄清楚是否有一種簡單的方法來顯示星期一的日期,給出了iso_week整數(和年份)。

我發現ISO8601 Convert Week Date to Calendar Date有幫助,但我不知道是否(或如何)一次爲多個值自動執行該過程。

這裏是我有的代碼的珍聞。理想情況下,我可以將另一個表達式添加到將顯示所需日期的select語句中。

 select STAFFID 
    , count(*) as appointment_ct 
    , datepart(iso_week, appointment_date) as iso_wk --this returns the week # of the year as an int 
    from [dbo].[view_APPT_DATA] 
    where program_code in ('99999') 
    and appointment_date >= '1/1/2016' and appointment_date <='3/31/2016' 
    group by iso_wk, STAFFID 

回答

0

我會找到first Monday of that year,然後使用DATEADD以週數增加那一天

select STAFFID 
, count(*) as appointment_ct 
, datepart(iso_week, appointment_date) as iso_wk --this returns the week # of the year as an int 
, dateadd(week, datepart(week, DATEADD(DAY, (@@DATEFIRST - DATEPART(WEEKDAY, dateadd(year, datepart(year, appointment_date) - 1900, 0)) + (8 - @@DATEFIRST) * 2) % 7, dateadd(year, datepart(year, appointment_date) - 1900, 0))) as monday_wk 
from [dbo].[view_APPT_DATA] 
where program_code in ('99999') 
and appointment_date >= '1/1/2016' and appointment_date <='3/31/2016' 
group by iso_wk, STAFFID, monday_wk 
+0

感謝@cha。這個想法很有效,儘管你的SQL給出了有關dateadd fxn的正確參數數量的錯誤。我最終在我的select語句中添加了「dateadd(wk,(iso_wk-1),'1/4/2016')」這個表達式,該語句沒有聲明變量,但當然取決於2016年。 – spearmint