现有一个表结构如下:
id  D1jh D1XH D2JH D2XH D3JH D3XH D4JH D4XH
001  2     2    3    3    4   4     5    5
002  4     4    5    5    6   6     7    7
现在要导入另一个表中
ID   DH    XH    JH
001  1     2     2
001  2     3     3
001  3     4     4
001  4     5     5
002  1     4     4
002  2     5     5
002  3     6     6
002  4     7     7
也就是将一条记录分离为4条记录,怎么写?     

解决方案 »

  1.   

    /*
    问题:如果上述两表互相换一下:即表结构和数据为:
    姓名 语文 数学 物理
    张三 74  83  93
    李四 74  84  94
    想变成(得到如下结果): 
    姓名 课程 分数 
    ---- ---- ----
    李四 语文 74
    李四 数学 84
    李四 物理 94
    张三 语文 74
    张三 数学 83
    张三 物理 93
    --------------
    */create table tb(姓名 varchar(10) , 语文 int , 数学 int , 物理 int)
    insert into tb values('张三',74,83,93)
    insert into tb values('李四',74,84,94)
    go--SQL SERVER 2000 静态SQL。
    select * from
    (
     select 姓名 , 课程 = '语文' , 分数 = 语文 from tb 
     union all
     select 姓名 , 课程 = '数学' , 分数 = 数学 from tb
     union all
     select 姓名 , 课程 = '物理' , 分数 = 物理 from tb
    ) t
    order by 姓名 , case 课程 when '语文' then 1 when '数学' then 2 when '物理' then 3 end--SQL SERVER 2000 动态SQL。
    --调用系统表动态生态。
    declare @sql varchar(8000)
    select @sql = isnull(@sql + ' union all ' , '' ) + ' select 姓名 , [课程] = ' + quotename(Name , '''') + ' , [分数] = ' + quotename(Name) + ' from tb'
    from syscolumns 
    where name! = N'姓名' and ID = object_id('tb') --表名tb,不包含列名为姓名的其它列
    order by colid asc
    exec(@sql + ' order by 姓名 ')
      

  2.   

    select id,d1jh as dh ,d1xh,as xh,1 as dh from ta  union all
    select id,d2jh,d2xh,2 from ta  union all
    select id,d3jh,d2xh,3 from ta unoin all
    select id,d4jh,d4xh,4 from ta
      

  3.   

    select id,dh=1,xh=d1jh,jh=d1xh from tab
              union all
              select id,dh=2,xh=d2jh,jh=d2xh from tab
              union all
               select id,dh=3,xh=d3jh,jh=d3xh from tab
              union all
              select id,dh=4,xh=d4jh,jh=d4xh from tab
              
      

  4.   

    --> 测试数据: #T
    if object_id('tempdb.dbo.#T') is not null drop table #T
    create table #T (id varchar(3),D1jh int,D1XH int,D2JH int,D2XH int,D3JH int,D3XH int,D4JH int,D4XH int)
    insert into #T
    select '001',2,2,3,3,4,4,5,5 union all
    select '002',4,4,5,5,6,6,7,7select ID,DH=1,XH=D1XH,JH=D1JH from #T
    union all
    select ID,DH=2,XH=D2XH,JH=D2JH from #T
    union all
    select ID,DH=3,XH=D3XH,JH=D3JH from #T
    union all
    select ID,DH=4,XH=D4XH,JH=D4JH from #T
    order by 1,2/*
    ID   DH    XH    JH
    001  1     2     2
    001  2     3     3
    001  3     4     4
    001  4     5     5
    002  1     4     4
    002  2     5     5
    002  3     6     6
    002  4     7     7
    */
      

  5.   


    select * from(
    select ID=id,DH=1,JH=D1JH,XH=D1XH from 表 union all
    select ID=id,DH=2,JH=D2JH,XH=D2XH from 表 union all
    select ID=id,DH=3,JH=D3JH,XH=D3XH from 表 unoin all
    select ID=id,DH=4,JH=D4JH,XH=D4XH from 表
    ) a
    order by ID,DH