想要的最终结果是
ReportDate  TagName            1     2 ...     8    ...   10 ........13      14 .....
2012-12-25  QLJ.PIA_101       191  2468.596 
2012-12-25  MMRDC.B1LT8103A                 86394.453
2012-12-25  MMRDC.B2LT8103A                             86398.438
2012-12-25  QLJ.TI_101                                             385.219   4133.108
.
.
.
.
不知道有没有表达清楚,空白地方0代替就OK

解决方案 »

  1.   

    select  ReportDate,TagName,
            max(case RangeID when 1 then LastTime_TotalSeconds else 0 end) as 1,
            max(case RangeID when 2 then LastTime_TotalSeconds else 0 end) as 2,
            max(case RangeID when 3 then LastTime_TotalSeconds else 0 end) as 3,
            .
            .
            .
    from  tb
    group by  TagName,ReportDate
      

  2.   

    declare  @sql varchar(8000)   
    select   @sql=isnull(@sql+',','')+' max(case RangeID when '''+RangeID+''' then LastTime_TotalSeconds else 0 end) ['+RangeID+']'  from (select distinct  RangeID from tb)as a         
    set  @sql='select ReportDate,TagName,'+@sql+' from tb group by TagName,ReportDate'  
    exec(@sql)
      

  3.   

    --SQL 2005 以上版本
    declare @sql varchar(8000)   
    set     @sql=''  --初始化变量@sql   
    select  @sql=@sql+','+ RangeID  from tb group by RangeID --变量多值赋值  
     set    @sql=stuff(@sql,1,1,'')--去掉首个','   
     set    @sql='select * from tb pivot (max(LastTime_TotalSeconds) for RangeID in ('+@sql+'))a'  
    exec(@sql)
      

  4.   

    忘记贴列类型了
    CREATE TABLE [dbo].[RmisEvo_CompareCensus](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [ReportDate] [datetime] NULL,
    [TagName] [nvarchar](50) NULL,
    [RangeID] [int] NULL,
    [LastTime_TotalSeconds] [decimal](18, 3) NULL
    ) ON [PRIMARY]
      

  5.   

    select  ReportDate,TagName,
            max(case RangeID when 1 then LastTime_TotalSeconds else 0 end) as '1',
            max(case RangeID when 2 then LastTime_TotalSeconds else 0 end) as '2',
            .
            .
            .
    from  tb
    group by  TagName,ReportDate
    字符