sql多表查询多字段相加。请sql大虾们帮帮忙!

表一:table1
fd_id fd_create_num fd_total_score fd_month fd_person_id
12 2 4 201108 54
13 3 6 201108 51
14 1 2 201108 81

表二:table2

fd_id fd_bp_create_num fd_bp_score fd_month fd_person_id
32 1 1 201108 54
56 3 1 201108 51
57 6 6 201108 87

我现在想查询出月份为201108的每个人的 fd_bp_score和 fd_total_score 的总分,比如人员Id为51的人,总分数是fd_total_score 加上fd_bp_score,总分为6+1=7分,人员87号,只有table2中有分,所以总分只有6分。
写了好多种,都感觉不对。谁能帮个忙?
要的格式就是:月份fd_month, 人员fd_person_id, fd_create_num,fd_total_score,fd_bp_create_num,fd_bp_score,总分(fd_total_score+fd_bp_score)这样一个结果

select
t1.fd_month 月份,
t1.fd_person_id 人员,
t1.fd_create_num,
t1.fd_total_score,
t2.fd_bp_create_num
t2.fd_bp_score,
t1.fd_total_score+t2.fd_bp_score 总分
from table1 t1
join table2 t2
on(t1.fd_month =t2.fd_month and t1.fd_person_id=t2.fd_person_id)追问

但是,如果某条数据,只有其中一个表里有,分数为null的时候,总分也是null,这个有问题。

追答

select
t1.fd_month 月份,
t1.fd_person_id 人员,
t1.fd_create_num,
isnull(t1.fd_total_score,0) fd_total_score,
t2.fd_bp_create_num
isnull(t2.fd_bp_score,0) fd_bp_score,
isnull(t1.fd_total_score,0)+isnull(t2.fd_bp_score,0) 总分
from table1 t1
join table2 t2
on(t1.fd_month =t2.fd_month and t1.fd_person_id=t2.fd_person_id)

追问

哦,明白了,那如果table2里面还有个fd_type的字段,table2只能找出fd_type=2数据再和table1相比。我加上去之后怎么这个条件也把table1的数据也约束了呢?

追答

因为用的是table1 join table2
join,是连接操作的意思,就是根据on的条件取table1和table2的记录的交集.

可以把
from table1 t1
join table2 t2
的join 改成 left join,这样这个条件就不会作用到table1上了.
left join表示左连接,根据on的条件取左侧表的全集,右侧表有对应记录的话,会连接右表的记录

追问

谢谢你的耐心,我明白你说的。不过我这个很特殊啊,table1和table2的数据都可能有对方表所没有的,所以我用的是full join 。而且,如果查询到某个确定的fd_month和某个确定的fd_person_id,带参数进去,就又不行了。

追答

那带参数的sql是什么样子的?
你说的不行是什么情况,表现为什么东西,语法错误还?查询结果不是想要的数据?

建议你把条件参数放在子查询里面

select
t1.fd_month 月份,
t1.fd_person_id 人员,
t1.fd_create_num,
isnull(t1.fd_total_score,0) fd_total_score,
t2.fd_bp_create_num
isnull(t2.fd_bp_score,0) fd_bp_score,
isnull(t1.fd_total_score,0)+isnull(t2.fd_bp_score,0) 总分
from (select * from table1 where .fd_month =@p_fd_month ) t1
join (select * from table2 where .fd_month =@p_fd_month ) t2
on(t1.fd_month =t2.fd_month and t1.fd_person_id=t2.fd_person_id)

温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-09-05
3
第2个回答  2011-09-05
使用笛卡尔乘积,left join连接2表,条件fd_month、fd_person_id
使用 when case判断fd_total_score 或fd_bp_score是否为null,为null则用0相加
相似回答