Share via

How to modify the first work date based on different group

Lora 200 Reputation points
2023-10-30T03:12:09.8733333+00:00

I have a table with employees from different group. Now I need to calculate the work date based on different group.

For example, employee from group 1 works from Monday to Friday every week. While employee from group 2 works from Sunday to Thursday.

Here is the demo table:

create table demo (employeeid int,groupid int,work_date datetime)
insert into demo values
(10011,1,'2023-10-30'),(10011,1,'2023-10-31'),(10022,2,'2023-10-30'),(10022,2,'2023-10-31')

The result should be like this:

User's image

Thanks in advance!

Developer technologies | Transact-SQL
Developer technologies | Transact-SQL

A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.

SQL Server | Other
SQL Server | Other

Additional SQL Server features and topics not covered by specific categories

0 comments No comments

Answer accepted by question author

LiHongMSFT-4306 31,621 Reputation points
2023-10-30T03:24:00.26+00:00

Hi @Lora

Try this:

-- Default Set Sunday is first day of week
set datefirst 7; 
select *,case when groupid = 1 then (datepart(weekday,work_date) + 5) % 7 + 1 
              when groupid = 2 then datepart(weekday,work_date)
			  end as day_of_week
from demo

Best regards,

Cosmog Hong


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

Note: Please follow the steps in our Documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?


0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.