数据库中的这样的记录
a1  0
a2  0
a3  0
b1  1
b2  1
怎样用sql语句检索后以下列数据集出现
a1  b1
a2  b2
a3  null

解决方案 »

  1.   

    不好意思
    字段名1  字段名2
     a1         0
     a2         0
     a3         0
     b1         1
     b2         1怎样用sql检索成下面的格式,字段为0的归一列,为1的归为别一列?
    a1  b1
    a2  b2
    a3  null
      

  2.   

    create table tb
    (
    字段名1 char(2),
    字段名2 int
    )
    insert into tb(字段名1,字段名2) values('a1',0)
    insert into tb(字段名1,字段名2) values('a2',0)
    insert into tb(字段名1,字段名2) values('a3',0)
    insert into tb(字段名1,字段名2) values('b1',1)
    insert into tb(字段名1,字段名2) values('b2',1)
    goselect id=identity(int,1,1) , 字段名1 into test1 from tb where 字段名2 = 0
    select id=identity(int,1,1) , 字段名1 into test2 from tb where 字段名2 = 1select test1.字段名1 as A , test2.字段名1 as B
    from test1 left join test2 on test1.id = test2.iddrop table tb
    drop table test1
    drop table test2A    B    
    ---- ---- 
    a1   b1
    a2   b2
    a3   NULL(所影响的行数为 3 行)
      

  3.   

    用一个sql不行吗,还要定义这个
    select id=identity(int,1,1) , 字段名1 into test1 from tb where 字段名2 = 0
    select id=identity(int,1,1) , 字段名1 into test2 from tb where 字段名2 = 1
    多个sql,我想要一个sql的,因为写在程序里
      

  4.   

    要想不加字段,必须有一个字段间的对应关系,如下:Select 
    a.字段名1,b.字段名1
    From tb a 
    Left Join tb b on Right(a.字段名1,1) = Right(b.字段名1,1)
    And b.字段名2 = 1
    Where a.字段名2 = 0字段名1 字段名1 
    ---- ---- 
    a1   b1
    a2   b2
    a3   NULL(所影响的行数为 3 行)
      

  5.   

    楼主用left join 或用*=方式
    declare @ta table 
    (
    字段名1 char(2),
    字段名2 int
    )
    insert into @ta(字段名1,字段名2) values('a1',0)
    insert into @ta(字段名1,字段名2) values('a2',0)
    insert into @ta(字段名1,字段名2) values('a3',0)
    insert into @ta(字段名1,字段名2) values('b1',1)
    insert into @ta(字段名1,字段名2) values('b2',1)
    --方法1
    select a.字段名1,b.字段名1
    from 
    (select * from @ta where 字段名2=0)a 
    left join 
    (select * from @ta where 字段名2=1)b on right(a.字段名1,1)= right(b.字段名1,1)
    --方法2
    select a.字段名1,b.字段名1
    from 
    (select * from @ta where 字段名2=0)a 
    ,
    (select * from @ta where 字段名2=1)b 
    where  right(a.字段名1,1)*= right(b.字段名1,1)
    字段名1 字段名1 
    ---- ---- 
    a1   b1
    a2   b2
    a3   NULL(所影响的行数为 3 行)