0

嗨,我在下面有一张表格,上面有活动和积分的记录

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    

然后我需要根据pointstable中的用户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

任何指针?

4

2 回答 2

2

使用外连接:

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
于 2013-11-01T15:56:56.463 回答
0

SELECT a.ActivityName,SUM( p.RemainderPoints) FROM activity a left join pointstable p on a.ActivityName =p.ActivityName WHERE p.UserID =2 AND p.Active = 'TRUE' and a.site ='Site1' GROUP BY a.ActivityName

希望这可以帮助!

于 2013-11-01T15:43:07.943 回答