SQL Server中具有time数据类型的动态数据透视表

时间:2017-11-17 08:58:05

标签: sql sql-server pivot sql-function

SELECT 
    PARTNO, BATCHNO, ' +   @IdleHoursColumns + '                              
INTO 
    TEMPTABLE_IH                            
FROM 
    [dbo].[PRODUCTION_IH]                               
PIVOT
    (SUM(IDLETIME))                              
          FOR REASON IN (' + @IdleHoursColumns + ')) AS P' 

--printed query 
SELECT 
    PARTNO, BATCHNO, [POWERCUT]                              
INTO 
    TEMPTABLE_IH                            
FROM 
    [dbo].[PRODUCTION_IH]                               
PIVOT
    (SUM(IDLETIME)                     
          FOR REASON IN ([POWERCUT])) AS P

如何在SQL Server中使用time数据类型的动态数据透视?我尝试将数据移动到临时表中,并将行值显示为动态列。该查询适用于整数数据类型列。但是我收到了错误

  

操作数数据类型时间对于sum运算符

无效

我尝试使用强制转换函数和Datediff,但它也会抛出错误。

2 个答案:

答案 0 :(得分:0)

如果您的数据类型不是数字,则应使用MAXMIN代替SUM

SELECT PARTNO,BATCHNO, ' +   @IdleHoursColumns + '                              
INTO TEMPTABLE_IH                            
FROM [dbo].[PRODUCTION_IH]                               
PIVOT( MAX(IDLETIME))                              
      FOR REASON IN (' + @IdleHoursColumns + ')) AS P' 

答案 1 :(得分:0)

尝试以下方法:

SELECT T1.PARTNO, T1.BATCHNO, T2.[POWERCUT] FROM (
SELECT PARTNO,BATCHNO,[POWERCUT]                              
    --INTO TEMPTABLE_IH                            
    FROM [DBO].[PRODUCTION_IH]                               
    PIVOT(MAX(IDLETIME)
          FOR REASON IN ([POWERCUT])) AS P)T1
    JOIN
    (
    SELECT PARTNO,BATCHNO, SUM(DATEDIFF(MINUTE, 0, IDLETIME)) / 60.0 AS [POWERCUT]
    FROM [DBO].[PRODUCTION_IH] 
    GROUP BY PARTNO,BATCHNO
    ) T2
ON T1.PARTNO = T2.PARTNO AND T1.BATCHNO = T2.BATCHNO

它会给你几小时的总时间。您可以对其进行修改以包括所有“原因”列。

HTH

感谢。