如何在数据透视表中使用SUM(CAST不能在聚合函数中使用)

时间:2014-05-19 03:54:00

标签: sql sql-server-2008 pivot-table

我正在使用以下数据透视查询:

    select UserId_Fk,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
      from CheckInCheckOut

    PIVOT
    (

     SUM(CAST(CountHours as decimal(18,2))) 
     FOR Day
     IN([Sunday],[Monday],[Tuesday],[Wednesday],[Thursday],[Friday],[Saturday])

    )
   as PivotTable

   Table[CheckInCheckOut]     

 CheckInCheckOutId  int 
    UserId_Fk       int 
  CountHours    nvarchar(50)    
         Day    nvarchar(50)    

我在这里使用SUM有些不对劲。我试过了

   select SUM(CAST(CountHours as decimal(18,2))) from CheckInCheckOut

给了我正确的结果,但是我无法在数据透视表中使用。

2 个答案:

答案 0 :(得分:2)

在进行透视查询之前尝试投射数据

  select UserId_Fk,Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday
      from    (Select UserId_Fk,CAST(CountHours as decimal(18,2))as CountHours,[Day]
   from CheckInCheckOut) as convertedtable

    PIVOT
    (

     SUM(CountHours) 
     FOR Day
     IN([Sunday],[Monday],[Tuesday],[Wednesday],[Thursday],[Friday],[Saturday])

    )
   as PivotTable

答案 1 :(得分:0)

由于我不使用sql-server / pivot,这只是一个猜测,但它不应该是那里的group by子句吗?即。

...
as PivotTable
group by UserId_Fk, ...