简体   繁体   English

mysql按天分组并计数,然后每天仅过滤最大值

[英]mysql group by day and count then filter only the highest value for each day

I'm stuck on this query. 我被这个查询卡住了。 I need to do a group by date, card_id and only show the highest hits. 我需要按日期进行分组,card_id仅显示最高的匹配。 I have this data: 我有此数据:

date        card_name     card_id   hits
29/02/2016  Paul Stanley    1345    12
29/02/2016  Phil Anselmo    1347    16
25/02/2016  Dave Mustaine   1349    10
25/02/2016  Ozzy            1351    17
23/02/2016  Jhonny Cash     1353    13
23/02/2016  Elvis           1355    15
20/02/2016  James Hethfield 1357    9
20/02/2016  Max Cavalera    1359    12

My query at the moment 我目前的查询

SELECT DATE(card.create_date) `day`, `name`,card_model_id, count(1) hits
FROM card
Join card_model ON card.card_model_id = card_model.id
WHERE DATE(card.create_date) >= DATE(DATE_SUB(NOW(), INTERVAL 1 MONTH)) AND card_model.preview = 0
GROUP BY  `day`, card_model_id 
;

I want to group by date, card_id and filter the higher hits result showing only one row per date. 我想按日期,card_id分组并过滤较高的匹配结果,显示每个日期仅显示一行。 As if I run a max(hits) with group by but I won't work 好像我通过group by运行max(hits),但我无法正常工作

Like: 喜欢:

date        card_name     card_id   hits
29/02/2016  Phil Anselmo    1347    16
25/02/2016  Ozzy            1351    17
23/02/2016  Elvis           1355    15
20/02/2016  Max Cavalera    1359    12

Any light on that will be appreciated. 任何光将不胜感激。 Thanks for reading. 谢谢阅读。

Here is one way to do this. 这是执行此操作的一种方法。 Based on your sample data (not the query): 根据您的样本数据(而不是查询):

select s.*
from sample s
where s.hits = (select max(s2.hits)
                from sample s2
                where date(s2.date) = date(s.date)
               );

Your attempted query seems to have no relationship to the sample data, so it is unclear how to incorporate those tables (the attempted query has different columns and two tables). 您尝试的查询似乎与示例数据没有关系,因此尚不清楚如何合并这些表(尝试的查询具有不同的列和两个表)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM