Mysql - 在一周内查找增加的值

时间:2014-04-24 07:03:03

标签: mysql

得分表


user_idx(int)

日期(日期时间)

得分(int)


我需要了解从今天开始的一周内总得分增加了多少。我知道我需要两个按user_idx分组的相同用户表,其中一个包含从过去到今天的总分,另一个包含从过去到一周之前的总分。

在那之后,通过从另一个中减去一个会给我答案......但是我很难写出有效的SQL查询。

我已经尝试了

SELECT BLAH BLAH 
FROM (SELECT user_idx, COUNT(*) as last_week_study_amount 
      FROM user_table 
      WHERE date <= date_sub(now(),INTERVAL 1 WEEK) 
      GROUP BY user_idx) 
AS a WHERE .....

你能帮助我吗?(?

2 个答案:

答案 0 :(得分:0)

让我清楚你想在上周得到总数。

尝试以下查询

SELECT *
FROM (SELECT user_idx, COUNT(*) as last_week_study_amount 
      FROM user_table 
      WHERE date <= date_sub(now(),INTERVAL 1 WEEK) 
      GROUP BY user_idx) 
AS a WHERE .....

答案 1 :(得分:0)

SELECT (SUM(score) - last_week_score) AS increased_score, 
FROM user a
JOIN (SELECT b.user_idx, COUNT(*) as last_week_score
  FROM userb
  WHERE date<= date_sub(now(),INTERVAL 1 WEEK)
  GROUP BY b.user_idx) As c ON a.user_idx = c.user_idx
WHERE DATE(date) <= DATE(NOW())
GROUP BY a.user_idx

我最后编写了这段代码,我觉得这个代码工作正常......不确定它是最好还是有严重错误。如果结果不好,我会更新它......