如题:
我有3个表结构如下
表1:
字段1 字段2 字段3
a b 5
d b 2
表2:
字段1 字段2 字段3
a b 3
表3
字段1 字段2 字段3
d b 4
数据存放在3个表,是由于不同业务存放的数据。
这3个表中的主健为字段1和字段2,我想得到的结果是
字段1 字段2 表1.字段3 表2.字段3 表3.字段3
a b 5 3 0
d b 2 0 4
...全文
1258打赏收藏
一个查询结果问题!在线等待
如题: 我有3个表结构如下 表1: 字段1 字段2 字段3 a b 5 d b 2 表2: 字段1 字段2 字段3 a b 3 表3 字段1 字段2 字段3 d b 4 数据存放在3个表,是由于不同业务存放的数据。 这3个表中的主健为字段1和字段2,我想得到的结果是 字段1 字段2 表1.字段3 表2.字段3 表3.字段3 a b 5 3 0 d b 2 0 4
'如下:a=表1,b=表2,c=表3,我已試過,完全沒問題!
select t.*,a.qty qty1,b.qty qty2,c.qty qty3 from
(select * from
(select rawt,rawn from a
union all
select rawt,rawn from b
union all
select rawt,rawn from c) temp
group by rawt,rawn) t
left join a on t.rawt=a.rawt and t.rawn=a.rawn
left join b on t.rawt=b.rawt and t.rawn=b.rawn
left join c on t.rawt=c.rawt and t.rawn=c.rawn
'如下:a=表1,b=表2,c=表3,我已試過,完全沒問題!
select t.*,a.qty qty1,b.qty qty2,c.qty qty3 from
(select * from
(select rawt,rawn from a
union all
select rawt,rawn from b
union all
select rawt,rawn from c) temp
group by rawt,rawn) t
left join a on t.rawt=a.rawt and t.rawt=a.rawt
left join b on t.rawt=b.rawt and t.rawt=b.rawt
left join c on t.rawt=c.rawt and t.rawt=c.rawt
insert into @b
select 'a','b',3
union
select 'd','b',5
insert into @c
select 'a','b',2
union
select 'd','b',4
select a.*,isnull(b.col3,0),isnull(c.col3,0),isnull(d.col3,0) from
(
select col1,col2 from @a
union
select col1,col2 from @b
union
select col1,col2 from @c) a
left join @a b on a.col1=b.col1 and a.col2=b.col2
left join @b c on a.col1=c.col1 and a.col2=c.col2
left join @c d on a.col1=d.col1 and a.col2=d.col2
如果出现这种情况
表1:
字段1 字段2 字段3
a b 5
表2:
字段1 字段2 字段3
a b 3
d b 5
表3:
字段1 字段2 字段3
a b 2
d b 4
上面的查询就不能得到这种结果了
字段1 字段2 表1.字段3 表2.字段3 表3.字段3
a b 5 3 2
d b 0 5 4