2

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

我有一个包含 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 之间的点

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

我读到了组合两个子查询进行计算,但未能实现它。

任何帮助表示赞赏。

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;
4

2 回答 2

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组合记录。

于 2012-06-24T15:35:43.610 回答
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
于 2012-06-24T15:49:51.170 回答