PIVOT语句错误

时间:2017-06-28 04:21:45

标签: tsql pivot

我无法通过以下数据集<{p}}开始工作PIVOT

Machine   AtTime                     ValueString
-------------------------------------------------
3     2017-06-01 11:42:33.000         Start

3     2017-06-01 11:43:46.000         Stop

5     2017-06-01 12:42:33.000         Start

5     2017-06-01 12:43:46.000         Stop

SQL

SELECT Machine, TimeStart, TimeEnd
FROM
(
      SELECT  Machine, [AtTime], [ValueString]
  FROM [dbo].[DATA_ACTION]
)
) d
PIVOT
(
  MAX(AtTime)
  FOR [AtTime] in (TimeStart, TimeEnd)
) piv;

错误

  

将数据类型nvarchar转换为datetime时出错。

目标

获取这样的表格

Machine  TimeStart                  TimeEnd
------------------------------------------------------------
3        2017-06-01 11:42:33.000    2017-06-01 11:43:46.000
5        2017-06-01 12:42:33.000    2017-06-01 12:43:46.000

1 个答案:

答案 0 :(得分:1)

您应该使用Valuestring:

create table data_action(Machine  nvarchar(50), AtTime datetime,ValueString nvarchar(50))
insert into data_action values (3,'2017-06-01 11:42:33.000','Start')
insert into data_action values (3,'2017-06-01 11:43:46.000','Stop')
insert into data_action values (5,'2017-06-01 12:42:33.000','Start')
insert into data_action values (5,'2017-06-01 12:43:46.000','Stop')


SELECT machine,start as [TimeStart],stop as [TimeEnd]
FROM
(
 SELECT  Machine, [AtTime], [ValueString]
  FROM [dbo].[DATA_ACTION]
) d
PIVOT
(
  MAX(AtTime)
  FOR [ValueString] in ([Start] , [Stop])
) piv;

结果是:

*---------*-------------------------*------------------------*   
|machine  |TimeStart                |TimeEnd                 | 
*---------*-------------------------*------------------------*      
|3        |2017-06-01 11:42:33.000  |2017-06-01 11:43:46.000 | 
*---------*-------------------------*------------------------*      
|5        |2017-06-01 12:42:33.000  |2017-06-01 12:43:46.000 |
*---------*-------------------------*------------------------*