Populate a column in SQL Server by weekday or weekend depending on the datetime

99封情书 提交于 2019-12-12 04:53:34

问题


I am working on SQL Server, wherein I cannot update any existing column nor can I add any more data/ column to the data.

I have a column of dttime (yyyy-mm-dd hh:mm:ss) which consists of the date time value against each entry. I want to select the existing columns , and a new column as wd which will be populated as 'weekend' when the day of the week is either Saturday or Sunday and 'weekday' in case of other days

I am using the below query:

SELECT id, total,
case when dayofweek(dttime) in (1,7) then 'Weekend' else 'Weekday' end as wd 
from table_name

Please suggest where is the mistake here, or is there any alternative to this, in case I have more than two different things to populate in a similar way, based on another column.


回答1:


You can use DATENAME of dw or weekday to achieve your expectation:

SELECT id, total, 
       CASE WHEN DATENAME (dw, dttime) IN ('Saturday', 'Sunday') THEN 'Weekend' 
       ELSE 'Weekday' END AS wd
FROM table_name

Also your first day of the week can be set by the SET DATEFIRST, so based on the DATEFIRST set value the integer value for Sunday and Saturday can change. So getting DATENAME for the dttime will not cause any confusion.

You can execute the below query to understand more in detail, DATENAME will always return the current day name, but DATEPART will return based on the DATEFIRST.

SELECT @@DATEFIRST AS 'First Day', 
       DATEPART(dw, GETDATE()) AS 'Today', 
       DATENAME(dw, GETDATE()) AS 'TodayName';

If SELECT @@DATEFIRST returns 7, then you can use

CASE WHEN DATEPART(dw, dttime) IN (1, 7) THEN 'Weekend' ELSE 'Weekday' END AS wd

Here 1 for Sunday and 7 for Saturday.




回答2:


You need DATEPART function. try this :

SELECT id, total,
case when DATEPART(dw,dttime) in (6,7) then 'Weekend' else 'Weekday' end as wd 
from table_name



回答3:


Please try below query

SELECT id, total,
case when DATEPART(dw,dttime) in (1,7) then 'Weekend' else 'Weekday' end as wd 
from table_name


来源:https://stackoverflow.com/questions/44899473/populate-a-column-in-sql-server-by-weekday-or-weekend-depending-on-the-datetime

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!