我正在尝试进行查询,以便在整个月(30天)内返回每位员工的结果。 数据如下:
employeeID day DayDutyDate fromTime Period
1 26 2014-03-26 2000-01-01 09:30:00.000 Time1
1 26 2014-03-26 2000-01-01 14:00:00.000 Time2
1 27 2014-03-27 2000-01-01 09:30:00.000 Time1
1 27 2014-03-26 2000-01-01 14:00:00.000 Time2
我正在按照以下日期进行调整:
PIVOT ( MIN(fromtime) FOR days IN ( [26],[27]) (I am being breif not listing all month days right now)
结果如下:
EmployeeID 26 27
1 2000-01-01 09:30:00.000 null
1 2000-01-01 14:00:00.000 null
1 null 2000-01-01 09:30:00.000
1 null 2000-01-01 14:00:00.000
我需要的是:
EmployeeID 26 27
1 2000-01-01 09:30:00.000 2000-01-01 09:30:00.000
1 2000-01-01 14:00:00.000 2000-01-01 14:00:00.000
有什么想法吗?
答案 0 :(得分:0)
此查询:
SELECT employeeID, [26], [27], Period
FROM
(SELECT employeeID, [day], fromtime, Period
FROM #MyTable) p
PIVOT
(
MIN(fromtime)
FOR [day] IN
( [26], [27])
) AS pvt
生成此输出:
employeeID 26 27 Period
==================================================================
1 2000-01-01 09:30:00.000 2000-01-01 09:30:00.000 Time1
1 2000-01-01 14:00:00.000 2000-01-01 14:00:00.000 Time2
答案 1 :(得分:0)
您还可以使用动态SQL来透视数据。见下面的例子:
DECLARE @cols as varchar(max)
DECLARE @sql as varchar(max)
SELECT @cols = coalesce(@cols + ',','') + '[' + day + ']' FROM #MyTable
SET @sql =
'SELECT employeeID, ' + @cols + ', Period
FROM (
SELECT employeeID, [day], fromtime, Period
FROM #MyTable
) as P
PIVOT
(
MIN(fromtime)FOR [day] IN (' + @cols + ')
)AS pvt'
EXEC(@sql)