诚心求教,谢谢了!
在一张表内,做成另外一个表。表结构如下
表  name  item1   item2  item3
     a     1        2      3
     a     4        5      6
     a     7        8      9
     b     11       12     13
     b     14       15     16
     c     21       22     23 这里面在name下同一个有多条记录,我想做成
 这样的表
    name    item1   item2  item3  item4   item5  item 6 item7   item8  item 9
     a        1        2      3     4        5      6     7        8      9
     b        11       12     13    14       15     16
     c        21       22     23 
请问应该怎么操作啊????
多谢了!!!

解决方案 »

  1.   

    ---测试数据---
    if object_id('[tb]') is not null drop table [tb]
    go
    create table [tb]([name] varchar(1),[item1] int,[item2] int,[item3] int)
    insert [tb]
    select 'a',1,2,3 union all
    select 'a',4,5,6 union all
    select 'a',7,8,9 union all
    select 'b',11,12,13 union all
    select 'b',14,15,16 union all
    select 'c',21,22,23
     
    ---查询---
    select 
      *
    from 
      tb a
    left join
      tb b
    on a.name=b.name and a.item1=b.item1-3
    left join 
      tb c
    on a.name=c.name and a.item1=c.item1-6
    where
      not exists(select 1 from tb where name=a.name and item1<a.item1)---结果---
    name item1       item2       item3       name item1       item2       item3       name item1       item2       item3       
    ---- ----------- ----------- ----------- ---- ----------- ----------- ----------- ---- ----------- ----------- ----------- 
    a    1           2           3           a    4           5           6           a    7           8           9
    b    11          12          13          b    14          15          16          NULL NULL        NULL        NULL
    c    21          22          23          NULL NULL        NULL        NULL        NULL NULL        NULL        NULL(所影响的行数为 3 行)
      

  2.   

    调一下格式---查询---
    select 
      a.name,a.item1,a.item2,a.item3,
      isnull(ltrim(b.item1),'') as item4,isnull(ltrim(b.item2),'') as item5,isnull(ltrim(b.item3),'') as item6,
      isnull(ltrim(c.item1),'') as item7,isnull(ltrim(c.item2),'') as item8,isnull(ltrim(c.item3),'') as item9
    from 
      tb a
    left join
      tb b
    on a.name=b.name and a.item1=b.item1-3
    left join 
      tb c
    on a.name=c.name and a.item1=c.item1-6
    where
      not exists(select 1 from tb where name=a.name and item1<a.item1)---结果---
    name item1       item2       item3       item4        item5        item6        item7        item8        item9        
    ---- ----------- ----------- ----------- ------------ ------------ ------------ ------------ ------------ ------------ 
    a    1           2           3           4            5            6            7            8            9
    b    11          12          13          14           15           16                                     
    c    21          22          23                                                                           (所影响的行数为 3 行)