我有两张桌子。
表1(abc)包含这些列
____________________________
|__id__|__userid__|__points__|
|__1__ |_____2____|____30____|
|__2__ |_____2____|____50____|
|__3__ |_____3___ |____40____|
表2(xyz)
________________________________
|__id__|__userid__|__usedpoints__|
|__1__ |_____2____|______10______|
|__2__ |_____3____|______20______|
|__3__ |_____2___ |______15______|
如何从这两个表中获取这样的记录?
_________________________________________
|__userid__|__totalpoints__|__usedpoints__|
|____2____ |_______80______|______25______|
|____3____ |_______40______|______20______|
答案 0 :(得分:4)
select u1.userid, sum(u1.points) as totalpoints, u2.usedpoints
from table1 u1
left join
(
select userid, sum(usedpoints) as usedpoints
from table2
group by userid
) u2 on u1.userid = u2.userid
group by u1.userid