嗨,我在下面的表格中记录了活动和分数
Activites |A_ID |Site | ActivityValue| ActivityName --------------------------------------------------- |1 | site1 | 7 | ActivityName1 |2 | site1 | 6 | ActivityName2 |2 | site1 | 6 | ActivityName3 |2 | site1 | 6 | ActivityName4 pointsTable |UserID |RemainderPoints | Active | ActivityName | ------------------------------------------------------ |1 | 10 | TRUE | ActivityName1| |2 | 5 | TRUE | ActivityName2| |2 | 5 | TRUE | ActivityName3| |2 | 5 | TRUE | ActivityName3|
我需要从活动中返回所有记录
SELECT ActivityName FROM activity WHERE `Site`='Site1'
退货
ActivityName1 ActivityName2 ActivityName3 ActivityName4
然后我需要基于来自点表的用户ID对用户点求和
SELECT UserID, ActivityName, Active, SUM( RemainderPoints) FROM pointstable WHERE UserID =2 AND Active = 'TRUE' GROUP BY ActivityName
|UserID |RemainderPoints | Active | ActivityName | ------------------------------------------------------------- |2 | 5 | TRUE | ActivityName2| |2 | 10 | TRUE | ActivityName3|
一切都很好,但我需要将它们放在一起给用户,即
ActivityName1 = 0 ActivityName2 = 5 ActivityName3 =10 ActivityName4 = 0
有指针吗?
使用外部联接:
select a.activityName, coalesce(sum(pt.remainderPoints), 0) points from activities a left outer join pointsTable pt on pt.activityName = a.activityName and pt.UserID = 2 group by a.activityName
或子查询:
select activities.ActivityName, coalesce( (select sum(RemainderPoints) from pointsTable where pointsTable.UserId = 2 and pointsTable.ActivityName = activities.ActivityName) , 0) points from activities