由於datepart(week,datefield)
功能系統會根據週日的週數作爲一週的第一天,所有你需要做的是檢查datepart(weekday,datefield)
,如果是1(星期日)或2(星期一),從datepart(week,datefield)
函數中減去1:
update table
set weeknumberofyear = datepart(week,datefield) -
case when datepart(weekday,datefield) in(1,2) then 1 else 0 end
編輯這並不佔年的時候週日或週一是一年的第一天。在這些情況下,您將得到0爲weeknumberofyear
。要解決此問題,請對錶格執行第二次更新。儘管這需要兩次更新,但我仍然認爲它比循環遍歷所有記錄更高效。
update table
set weeknumberoftheyear = weeknumberoftheyear + 1
where year(datefield) in(
select distinct year(datefield)
from table
where weeknumberoftheyear = 0
)
編輯 WeekNumberOfTheMonth更新 - 現在,我們有WeekNumberOfTheYear值,我們可以使用在該領域排名函數沒有任何遞歸更新WeekNumberOfTheMonth列。
update t
set t.weeknumberofthemonth = u.weeknumberofthemonth
from table t
inner join (
select distinct weeknumberoftheyear,
dense_rank() over(partition by month(datefield)
order by weeknumberoftheyear) weeknumberofthemonth
from table) u
on u.weeknumberofyear = t.weeknumberofyear
你可以改寫你的問題,使其更清晰?我讀了五次,我不明白。 –
您想要將週數計爲週一的第一天,對吧?請參閱下面的答案。 –