急!!!!数据库查询
现有一个表的字段:借码 借钱 贷码 贷钱
101 50 109 50
101 100 103 100
102 40 101 40
我希望查询后得到这样的结果并把这个结果存入一个表中(这个表随查询建立)
代码 借钱 贷钱
101 150 40
102 40 0
103 0 100
109 0 50
请大家帮看看!!!很感谢!
------解决方案--------------------select 借码 as 代码,nz(a.借钱,0) as 借钱,nz(b.贷钱,0) as 贷钱 from (
SELECT 借码,sum(tt.借钱) as 借钱 from tt group by 借码 ) a
left join
(SELECT 贷码,sum(tt.贷钱) as 贷钱 from tt group by 贷码 ) b
on b.贷码=a.借码
union
select 贷码 as 代码,nz(借钱,0),nz(贷钱,0) from (
SELECT 借码,sum(tt.借钱) as 借钱 from tt group by 借码 ) a
right join
(SELECT 贷码,sum(tt.贷钱) as 贷钱 from tt group by 贷码 ) b
on b.贷码=a.借码