在SQL Server 2008 R2中的数据透视表中分组

时间:2015-02-03 15:53:36

标签: sql-server-2008-r2 sql-server-2012

如何按此数据透视表进行分组

select * 
from 
    (SELECT     
        ProductionID,ProductionDetailID,                
        [DeviceID],[DeviceSpeed],[LattNO] 
     from 
        (SELECT      
            * 
         from view_3 
         where ProductionID = 6) x pivot 
        (
            max(Value)FOR PropertyName  in ([DeviceID],[DeviceSpeed],[LattNO])
        )  AS pvt ) as  pp 

结果:

ProductionID  ProductionDetailID  DeviceID  DeviceSpeed  LattNO
6                     2             5           NULL      NULL
6                     2             NULL          8       NULL
6                     2             NULL         NULL      6
6                     3             1            NULL     NULL
6                     3             NULL          2       NULL

我怎样才能得到这个结果:

  ProductionID  ProductionDetailID  DeviceID  DeviceSpeed  LattNO
      6            2                  5          8          6
      6            3                  1          2          NULL

1 个答案:

答案 0 :(得分:1)

选择
ProductionID,ProductionDetailID,Sum(Cast(isnull([DeviceID],0)as Int))[DeviceID],Sum(Cast(isnull([DeviceSpeed],0)as Int))[DeviceSpeed],Case Sum(Cast(isnull) ([LattNO],0)为Int))当为0时,则为Null else Sum(Cast(isnull([LattNO],0)为Int))从[LattNO]结束             (                选择                *来自dbo.View_3
           )             x枢轴             (                 ([DeviceID],[DeviceSpeed],[LattNO])中的PropertyName的最大值(值)             )AS pvt 按ProductionID分组,ProductionDetailID