再次请教一个连接查询问题。谢谢大家!
之前发过一贴,可惜问题还是没解决,我把问题做了下简化,导致没表述清楚。
table2原始的数据是:
table1:
id value1
1 100
2 200
3 700
table2:
id value2
1 12
1 33
3 87
3 9
我想得到的结果是:
我想得到的查询结果为
id value1 value2
1 100 45
2 200 0 (或者显示null也行)
3 700 96
我的sql得不到2号记录,我的sql 是:
select a.id,a.value1,sum(b.value2) from table1 a left outer join table2 b on a.id=b.id where a.id in ('1','2','3') group by a.id,b.id,a.value1
select isnull(a.id,b.id) as id, isnull(a.value1,0),isnull(b.value2,0)from (select id,sum(value1) as value1 from table1 group by id) afull join (select id,sum(value2) as value2 from table2 group by id)bon a.id=b.id
[解决办法]
select A.id,A.value1,B.value2from table1 A left join (select id,sum(value2) as value2 as value2 from table2 group by id) Bon A.id = B.id
[解决办法]
--如果table1为基表,且id是全的,那么没必要用full join,试试下面的select a.*,b.value2 from table1 a left join (select id,sum(value2) value2 from table2group by id) b on (a.id=b.id)where a.id in ('1','2','3')