select rybh,
       jg,
       [mz]=(select label from b where name=a.mz and type='民族'),
       [xb]=(select label from b where name=a.xb and type='性别')
from a

解决方案 »

  1.   

    --创建测试环境
    create table a
    (
      rybh varchar(10),
      jg varchar(10),
      mz varchar(10),
      xb varchar(10)
    )
    create table b
    (
      name varchar(10),
      label varchar(10),
      type varchar(10)
    )
    insert a
    select '01','01','02','01' union
    select '02','01','01','01' union
    select '03','02','03','02' 
    insert b
    select '01','汉族','民族' union
    select '02','彝族','民族' union
    select '01','男','性别' --测试
    select rybh,
           jg,
           [mz]=(select label from b where name=a.mz and type='民族'),
           [xb]=(select label from b where name=a.xb and type='性别')
    from a
    --删除测试环境
    drop table a,b--结果
    /*
    rybh       jg         mz         xb         
    ---------- ---------- ---------- ---------- 
    01         01         彝族         男
    02         01         汉族         男
    03         02         NULL       NULL(所影响的行数为 3 行)
    */
      

  2.   

    SELECT a.rybh,
    jg=(SELECT b.label FROM b where b.type='民族' and [name]=a.jg),
    xb=(SELECT b.label FROM b where b.type='性别' and [name]=a.xb) 
    FROM a^_^
      

  3.   

    to :  vivianfdlpw  字段+ []有什么不同?还有其它方法吗,哪种效率更高一些?
      

  4.   

    [] 说明是字段,防止有些字段是sql的关键字
      

  5.   

    --vivianfdlpw()的方法应该不错了 很直观
      

  6.   

    select
        a.rybh,
        label = max(case when b.type='民族' and a.mz=b.name then b.label end),
        type  = max(case when b.type='性别' and a.xb=b.name then b.label end)
    from
        a,b
    group by
        a.rybh
      

  7.   

    to:libin_ftsafe(子陌红尘) 
    刚才测试了一下代码,如果不止一个类似rybh的字段,这段代码估计就不能满足要求,另该代码的速度太慢,不知能否优化?
      

  8.   

    回复人: cqulzh(Eexcelence) ( ) 信誉:100  2005-08-03 15:13:00  得分: 0  
     
     
       to:libin_ftsafe(子陌红尘) 
    刚才测试了一下代码,如果不止一个类似rybh的字段,这段代码估计就不能满足要求,另该代码的速度太慢,不知能否优化?1如果不止一个类似rybh的字段?
    这个字段代表什么意思,如果不止一个,就用 vivianfdlpw() 的代码2.我觉得似乎代码没有太大改善的空间
      

  9.   

    to  MorningTea(一勺抹茶)
    明白