I was trying to find a solution but did not succeed even if it seems simple. So this might be a newbie question...
我试图找到一个解决方案,但即使看起来很简单也没有成功。所以这可能是一个新手问题......
I have a table userscores with 3 columns:
我有一个包含3列的表用户核心:
date userid points
2012-05-01 1 23
2012-06-01 1 34
2012-07-01 1 44
2012-05-01 2 78
2012-06-01 2 94
2012-07-01 2 99
2012-06-01 3 2
2012-07-01 3 9
Now I need to get the difference of the points between 2012-05-01 and 2012-06-01 for each user.
现在我需要为每个用户获得2012-05-01和2012-06-01之间的差异。
Users' points that are not existing (example userid 3) have to be calculated as 2 - 0... for this I guess I can use COALESCE(qa_points,0).
用户不存在的点(示例用户ID 3)必须计算为2 - 0 ...为此我想我可以使用COALESCE(qa_points,0)。
I read about combining two subqueries for the calculation but failed implementing it.
我读到了将两个子查询组合起来进行计算但未能实现它。
Any help appreciated.
任何帮助赞赏。
PS: This is not working:
PS:这不起作用:
SELECT t1.userid, t1.points - t2.points AS mpoints FROM (
SELECT userid,points FROM `userscores`
WHERE YEAR(date) = YEAR('2012-05-01')
AND MONTH(date) = MONTH('2012-05-01') )
AS t1
JOIN (
SELECT userid,points FROM `userscores`
WHERE YEAR(date) = YEAR('2012-04-01')
AND MONTH(date) = MONTH('2012-04-01') )
AS t2
ORDER BY mpoints DESC, t1.userid DESC;
2 个解决方案
#1
2
I suppose your query will look like this:
我想您的查询将如下所示:
SELECT ul.userid,
ul.points - COALESCE(uf.points, 0) AS points_difference
FROM userscores ul
LEFT JOIN
(SELECT userid, points FROM userscores WHERE `date` = '2012-05-01') AS uf
ON uf.userid = ul.userid
WHERE ul.date = '2012-06-01'
LEFT JOIN is used because you told that there may be no records for this user/former date
combination.
使用LEFT JOIN是因为您告知此用户/以前的日期组合可能没有记录。
#2
0
Use this query:
使用此查询:
SELECT t1.userid,
( t1.points - (case t2.date when '2012-05-01' then t2.points else 0 end))
AS mpoints FROM userscores as t1
INNER JOIN userscores as t2
ON t1.date = '2012-06-01' AND t1.userid=t2.userid
#1
2
I suppose your query will look like this:
我想您的查询将如下所示:
SELECT ul.userid,
ul.points - COALESCE(uf.points, 0) AS points_difference
FROM userscores ul
LEFT JOIN
(SELECT userid, points FROM userscores WHERE `date` = '2012-05-01') AS uf
ON uf.userid = ul.userid
WHERE ul.date = '2012-06-01'
LEFT JOIN is used because you told that there may be no records for this user/former date
combination.
使用LEFT JOIN是因为您告知此用户/以前的日期组合可能没有记录。
#2
0
Use this query:
使用此查询:
SELECT t1.userid,
( t1.points - (case t2.date when '2012-05-01' then t2.points else 0 end))
AS mpoints FROM userscores as t1
INNER JOIN userscores as t2
ON t1.date = '2012-06-01' AND t1.userid=t2.userid