获得每个日期的最高价值

时间:2016-04-28 12:49:12

标签: mysql sql database mysql-workbench

我有一个表,每次用户完成调查时都会记录。看起来有点像这样:

    surveyID        author       timestamp
-----------------------------------------------
    1               person1      1461840669000
    2               person2      1461840670000
    3               person1      1461840680000

我正在尝试运行一个查询,自4月1日起每天向我展示顶级测量员(即每天调查次数最多的人)。

到目前为止,我已经尝试过这个:

SELECT author,
       COUNT (DISTINCT surveyid) AS num_surveys,
       STRFTIME_UTC_USEC(creation_time*1000, "%Y-%m-%d") AS date,
FROM myTable
WHERE creation_time > 1459468800000 //since April 1st
GROUP BY date, author
ORDER BY 3 DESC,2 DESC;

这给了我这个结果:

author     num_surveys       date
------------------------------------
user1      116            2016-04-27
user2      109            2016-04-27
user3      99             2016-04-27
user3      102            2016-04-28
user1      98             2016-04-28
user2      97             2016-04-28

但是,我真的很喜欢每天的最高记录:

author     num_surveys       date
------------------------------------
user1      116            2016-04-27
user3      102            2016-04-28   etc...

我在不同的地方尝试了MAX()TOP(),但是到目前为止我们都没有工作过,因此上面的查询示例让我最接近我想要的...任何建议都会非常感谢。我是SQL的新手!

修改

感谢远远的建议。设法让它与之合作:

DEFINE INLINE TABLE A
SELECT author,
COUNT (DISTINCT featureid) AS num_surveys,
STRFTIME_UTC_USEC(creation_time*1000, "%Y-%m-%d") AS date,
FROM placesense.surveys
WHERE creation_time > 1459468800000
GROUP BY date, author
ORDER BY 3 DESC,2 DESC;

SELECT
MAX(num_surveys),
date
FROM A AS B
WHERE date = B.date
GROUP BY date

欢迎任何其他更有效的建议。

2 个答案:

答案 0 :(得分:0)

一种非常简单的方法是使用相关的子查询:

select t.*
from t
where t.num_surveys = (select max(t2.num_surveys) from t t2 where t2.date = t.date);

注意:如果是关系,这将返回日期的重复项。

答案 1 :(得分:0)

SELECT MAX( surveyid) AS m_surveys,
       STRFTIME_UTC_USEC(creation_time*1000, "%Y-%m-%d") AS date,
FROM myTable
WHERE creation_time > 1459468800000 //since April 1st
GROUP BY date, author
ORDER BY 3 DESC,2 DESC;