求一个查询,急
有两个表
表A:字段1,字段2,字段3
A 11 12
B 21 22
C 31 32
表B:字段a,字段b,字段c
A 1 E
A 2 F
B 1 F
B 2 E
C 1 E
C 2 F
求一个查询,得到表(字段4为表B中字段b值等于1的,字段5为表B中字段b值等于2的)
字段1,字段2,字段3,字段4,字段5
A 11 12 E F
B 21 22 F E
C 31 32 E F
------解决方案--------------------declare @a table(name1 varchar(20),name2 int,name3 int)
insert @a
select 'a ',11,12
union all
select 'b ',21,22
union all
select 'c ',31,32
declare @b table(name1 varchar(20),name2 int,name3 varchar(20))
insert @b
select 'a ',1, 'e '
union all
select 'a ',2, 'f '
union all
select 'b ',1, 'f '
union all
select 'b ',2, 'e '
union all
select 'c ',1, 'e '
union all
select 'c ',2, 'f '
select * from @a c,
(select a.name1,a.name3,b.name3 as name4 from @b a ,@b b where a.name1=b.name1 and a.name2 <b.name2) d
where c.name1=d.name1
/*
name1 name2 name3 name1 name3 name4
-------------------- ----------- ----------- -------------------- -------------------- --------------------
a 11 12 a e f
b 21 22 b f e
c 31 32 c e f
(所影响的行数为 3 行)
*/