一个查询结果问题!在线等待

pjjia 2004-06-29 02:47:54
如题:
我有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
...全文
125 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
pjjia 2004-07-01
  • 打赏
  • 举报
回复
谢谢 victorycyz(中海) , csdnwhycn() ,Relta(芯片)
yyd415 2004-06-29
  • 打赏
  • 举报
回复
select a.*,b.字段3,c.字段3
from [表1] a left join [表2] b on a.字段1=b.字段1 and a.字段2=b.字段2
left join [表3] c on a.字段1=c.字段1 and a.字段2=c.字段2
Relta 2004-06-29
  • 打赏
  • 举报
回复
'如下: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
FlyNesta 2004-06-29
  • 打赏
  • 举报
回复
select s.*,
case when b.字段3 is NULL then 0 else b.字段3 end as 字段3
case when c.字段3 is NULL then 0 else c.字段3 end as 字段3

from 表1 a left join 表2 b on a.字段1=b.字段1 and a.字段2=b.字段2
left join 表3 c on a.字段1=c.字段1 and a.字段2=c.字段2
Relta 2004-06-29
  • 打赏
  • 举报
回复
'如下: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
csdnwhycn 2004-06-29
  • 打赏
  • 举报
回复

declare @a table (col1 nchar(2),col2 nchar(2),col3 int)
declare @b table (col1 nchar(2),col2 nchar(2),col3 int)
declare @c table (col1 nchar(2),col2 nchar(2),col3 int)
insert into @a
select 'a','b',5

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

pjjia 2004-06-29
  • 打赏
  • 举报
回复
如果出现这种情况
表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
victorycyz 2004-06-29
  • 打赏
  • 举报
回复
select a.*,b.字段3,c.字段3
from table1 a left join table2 b on a.字段1=b.字段1 and a.字段2=b.字段2
left join table3 c on a.字段1=c.字段1 and a.字段2=c.字段2

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧