原表
 id         Name            value
1000    东北    1
1000    东南              2
1000        华北              3
1001    东北    1
1001    东南              2
1001        华北              3
1002    东北    1
1002    东南              2sql语句查询出来如下 id        东北      东南     华北   
1000        1          2       3
1001        1          2       3
1002        1          2      NULL 请高手指教 sql语句该怎么写

解决方案 »

  1.   

    http://topic.csdn.net/u/20080509/14/6ed10765-32a8-45cd-99e8-c4a623d315e1.html
      

  2.   

    declare @sql nvarchar(max)
    set @sql=' select distinct id'
    select @sql=@sql+',value as ['+Name+'] ' from (select distinct Name from table1 ) as aa
    select @sql=@sql+'  from table1 group by id,value'
    exec(@sql)由于我在红字部分没用聚合函数  所以后面分组的时候就必须加上 value 这个字段
    但这样 查出来 就不对了 请问该怎么改
      

  3.   

    http://topic.csdn.net/u/20100412/22/fec647ea-73d0-480b-92e9-8af61ef3c978.html
      

  4.   

    对头 SQL行转列 搜搜去吧
      

  5.   

    declare @sql nvarchar(max)
    set @sql=' select distinct id'
    select @sql=@sql+',max(case value when ''' + value + ''' then value else 0 end) as ['+Name+'] '
     from (select distinct Name,value from table1 ) as aa
    select @sql=@sql+'  from table1 group by id'
    exec(@sql)谢谢各位了  搞定了