Home > Blockchain >  How to create columns for days of the week?
How to create columns for days of the week?

Time:10-22

The database I am working with has a separate entry an employee's start time each day. I want to create columns for the start on each day of the week - "Monday Start Time", "Tuesday Start Time", etc. Example of the table schema I'm working with

I tried this but it returns multiple results in the subquery:

select "Employee Number", "Employee Name"
  , (select `Start Time` from start_times WHERE `Day` = "Monday") AS "Monday Start"
from start_times

Example Desired Output

CodePudding user response:

The simplest approach is a PIVOT:

SELECT * FROM dbo.MyTable
PIVOT 
(
  MAX([Start Time]) FOR [Day] IN 
  ([Monday],[Tuesday],[Wednesday],[Thursday],[Friday])
) AS p;

The results aren't exactly as you wanted but you can apply whatever column labels you want after the fact.

Working example in this fiddle.

  • Related