我正在创建一个计划应用程序,允许员工输入存储在表格中的所需计划。我正在看的当前设计如下,使用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
)
)
需要注意的一些事项
以下是样本数据
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
我想要的输出是这样的
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
我之前从未使用PIVOT
查询,因为我们刚从SQL 2000升级,所以请耐心等待。我构造了下面的查询,但由于出现以下错误而失败,我被卡住了。
Msg 102, Level 15, State 1, Line 14
Incorrect syntax near '('.
查询
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
关于如何最好地实现这个或者我在这里有多么严重错误的任何想法?
答案 0 :(得分:2)
看起来您正试图根据1-7周的日期来截取您的数据。我建议稍微修改一下以使其工作:
SELECT *
FROM
(
select EmpNum,
reason,
datepart(dw, start) as DyOfWk
from #Schedule
) s
pivot (
max(Reason)
for dyofwk in ([1], [2], [3], [4], [5], [6], [7])
) as Pvt
结果: