具有日期过滤器的每个用户的最高得分

时间:2013-07-23 13:08:24

标签: php

例如我有以下表格结构

 userid  |  score  |      datestamp      |
-----------------------------------------------------
   1     |   44    |  2013-06-01 14:25:55 
   1     |   50    |  2013-06-02 14:25:55 
   2     |   59    |  2011-06-04 09:25:51 
   1     |   60    |  2011-06-10 21:25:15 
   3     |   19    |  2011-06-02 07:25:18
   2     |   70    |  2011-06-05 09:25:51 
   2     |   12    |  2011-06-08 09:25:51 
   3     |   60    |  2011-06-05 07:25:18
   4     |   30    |  2011-06-10 07:25:18
   3     |   20    |  2011-06-08 07:25:18
   4     |   15    |  2011-06-09 07:25:18
   1     |   50    |  2013-06-11 14:25:55 
   2     |   100   |  2013-06-15 14:25:55 
   3     |   160   |  2013-06-12 14:25:55 
   4     |   75    |  2013-06-16 14:25:55 

我需要这样一个查询,其中我将给出日期限制,它将给出我在此期间每个用户的最高分数。 例如,如果我给出开始日期2013-06-01和结束日期2011-06-10,它将导致:

 userid  |  score  |      datestamp      |
----------------------------------------------------- 

  1     |   60    |  2011-06-10 21:25:15 

  2     |   70    |  2011-06-05 09:25:51 

  3     |   60    |  2011-06-05 07:25:18

  4     |   30    |  2011-06-10 07:25:18 

此外,如果我也给用户ID(使用IN(1,2,3,4))

,那将会很棒

2 个答案:

答案 0 :(得分:2)

如果您不需要相应的日期,只需要最高分,这将有效

SELECT
    userid, MAX(score)
FROM
    tablename
WHERE
    datestamp BETWEEN '2011-06-10 00:00:00' AND '2013-06-01 23:59:59'
    -- AND userid IN (1, 2, 3, 4)
GROUP BY
    userid

获取与之相关的日期会更复杂。

答案 1 :(得分:1)

尝试此查询,

SELECT userid, MAX(score) as score FROM table 
WHERE datestamp BETWEEN '2011-06-10 00:00:00' AND '2013-06-01 23:59:59' AND userid IN(1,2,3,4)
GROUP BY userid