declare @boy table
(
  boyid int,name varchar(10)
)
declare @girl table
(
  girlid int,name varchar(10)
)declare @boy_girl table
(
  bgid int,name varchar(10),sex varchar(10)
)
insert @boy
select 1,'Tom' union all
select 2,'Ab' union all
select 3,'John' 
insert @girl
select 1,'Alice' union all
select 2,'Tand'
insert @boy_girl 
select 1,null,'男' union all
select 2,null,'女' union all
select 1,null,'女' union all
select 3,null,'男'--查询
select A.bgid
       ,B.name
       ,A.sex
from @boy_girl A
join (
        select *,'男' as 'sex' from @boy
        union all
        select *,'女' from @girl
     )B on A.bgid=B.boyid and A.sex=B.sex
--结果
/*
bgid        name       sex        
----------- ---------- ---------- 
1           Tom        男
2           Tand       女
1           Alice      女
3           John       男(所影响的行数为 4 行)
*/

解决方案 »

  1.   

    CREATE VIEW dbo.VIEW1
    AS
    select bgid,name=case sex='男' then b.name else c.name end ,sex from bor_girl a inner join boy b on a.bgid=b.boyid and a.sex='男' inner join girl c on a.bgid=c.girlid and a.sex='女' 
    c
    GO
      

  2.   

    create view vboy_girl as
    select * from (
    select boyid as 'bgid',name,'男' as sex from boy
    union all
    select girlid,name,'女' as sex from girl)aa
      

  3.   

    create view vboy_girl as
    select * from (
    select boyid as 'bgid',name,'男' as sex from boy
    union all
    select girlid,name,'女' as sex from girl)aa
      

  4.   

    create view vboy_girl
    as
    select bgid,name=
                case sex='男' 
                then b.name 
                else c.name 
                end ,
                sex 
    from girl a inner join boy b 
        on a.bgid=b.boyid and 
        a.sex='男' inner join girl c 
        on a.bgid=c.girlid and a.sex='女'