I am creating a scheduling application that allows employees to input their desired schedule which is stored in a table. The current design I’m looking at is below using SQL 2008 R2.
CREATE TABLE [dbo].[Schedule] (
[EmpNum] [varchar](10) NOT NULL,
[Start] [datetime] NOT NULL,
[Length] [decimal](18, 2) NOT NULL,
[Reason] [varchar](1) NOT NULL,
CONSTRAINT [PK_Schedule] PRIMARY KEY CLUSTERED
(
[EmpNum] ASC,
[Start] ASC
)
)
A few things to note
- A user may have entered no schedule for a specific date range and still want to see their name listed but with no schedule
- A user may select nothing for a day in a week, but select something for other days
- Start is the beginning of the shift
- Length is the number of hours a shift is, may vary WILDLY from day to day and person to person
- The Reason column is for what has been selected by the user (W – Work, P – PTO, etc)
Here is sample data
EmpNum Start Length Reason
---------- ----------------------- --------------------------------------- ------
000001 2012-08-02 09:00:00.000 12.00 W
000001 2012-08-04 08:00:00.000 9.50 P
000002 2012-08-02 08:30:00.000 10.00 W
000002 2012-08-03 19:00:00.000 12.00 W
000003 2012-08-03 08:00:00.000 8.00 P
The output I desire is something like this
EmpNum [0] [1] [2] [3] [4] [5] [6]
---------- ------ ------ ------ ------ ------ ------ ------
000001 NULL NULL NULL NULL W NULL P
000002 NULL NULL NULL NULL W W NULL
000003 NULL NULL NULL NULL NULL P NULL
I’ve never used a PIVOT query before since we just upgraded from SQL 2000, so bear with me. I’ve constructed the below query which fails with the below error and I’m stuck.
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near '('.
Query
declare @FirstDayOfWeek date
set @FirstDayOfWeek = '7/29/2012'
select EmpNum,
@FirstDayOfWeek [0],
dateadd(day, 1, @FirstDayOfWeek) [1],
dateadd(day, 2, @FirstDayOfWeek) [2],
dateadd(day, 3, @FirstDayOfWeek) [3],
dateadd(day, 4, @FirstDayOfWeek) [4],
dateadd(day, 5, @FirstDayOfWeek) [5],
dateadd(day, 6, @FirstDayOfWeek) [6]
from Schedule
pivot (
max(Reason)
for Start in ([0], [1], [2], [3], [4], [5], [6])
) as Pvt
Any thoughts on how to best implement this or how badly wrong I am here?
It looks like you are trying to PIVOT your data based on the Day of the Week 1-7. I suggest a slight change to this to get it to work:
See SQL Fiddle with Demo
Results: