MySQL:在一个表(多个用户)中获取两个值之间的差异?

时间:2012-06-24 15:16:55

标签: mysql

我试图找到一个解决方案,但即使看起来很简单也没有成功。所以这可能是一个新手问题......

我有一个表 userscores ,包含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

现在,我需要获得2012-05-01和2012-06-01 之间每个用户的差异

用户'不存在的点(示例用户ID 3)必须计算为2 - 0 ...为此我想我可以使用COALESCE(qa_points,0)。

我读到了将two subqueries组合起来进行计算但未能实现它。

任何帮助表示感谢。

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 个答案:

答案 0 :(得分:2)

我想您的查询将如下所示:

    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是因为您告知this user/former date组合可能没有记录。

答案 1 :(得分:0)

使用此查询:

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