求个SQL,多谢
求个SQL,谢谢
A表
字段1 字段2
A1 aaa
A2 bbb
B表
字段1 字段2 字段3
A1 测试1 1000
A2 测试2 500
想得出的结果
A1 测试1 1000
A2 测试2 0
A1 测试2 0
A2 测试2 500
------解决方案--------------------
A表
字段1 字段2
A1 aaa
A2 bbb
B表
字段1 字段2 字段3
A1 测试1 1000
A2 测试2 500
想得出的结果
A1 测试1 1000
A2 测试2 0
A1 测试2 0
A2 测试2 500
------解决方案--------------------
- SQL code
declare @A表 table (字段1 varchar(2),字段2 varchar(3)) insert into @A表 select 'A1','aaa' union all select 'A2','bbb' declare @B表 table (字段1 varchar(2),字段2 varchar(5),字段3 int) insert into @B表 select 'A1','测试1',1000 union all select 'A2','测试2',500 --是不是这个意思? select a.字段1,b.字段2, case when a.字段2='aaa' then 字段3 else 0 end as 字段3 from @A表 a cross join @B表 b /* 字段1 字段2 字段3 ---- ----- ----------- A1 测试1 1000 A2 测试1 0 A1 测试2 500 A2 测试2 0 */
------解决方案--------------------
- SQL code
select b.字段1, b.字段2, (case b.字段1 when 'A1' then b.字段3 else 0) from b left join a where a.字段1=b.字段1 union select b.字段1, b.字段2, (case b.字段1 when 'A2' then b.字段3 else 0) from b left join a where a.字段1=b.字段1
------解决方案--------------------
应该是2楼说的
------解决方案--------------------
2楼结果也不对,能把查询条件说一下吗