简体   繁体   English

MySQL计数自定义限制

[英]Mysql Count with Custom Limit

I'm making some report, my data look like this : 我正在报告,我的数据如下所示:

text    date                    text    date
a       18/01/2016 12:01        a       18/01/2016 13:01
b       18/01/2016 12:01        b       18/01/2016 13:01
c       18/01/2016 12:01        c       18/01/2016 13:01
d       18/01/2016 12:01        x       18/01/2016 13:01
e       18/01/2016 12:01        y       18/01/2016 13:01
f       18/01/2016 12:01        z       18/01/2016 13:01
g       18/01/2016 12:01        g       18/01/2016 13:01
h       18/01/2016 12:01        h       18/01/2016 13:01
i       18/01/2016 12:01        i       18/01/2016 13:01

To get the total number of text : 要获取文本总数:

SELECT *, COUNT(*) AS total FROM table 
WHERE DAY(date) = DAY('2016-01-18') 
AND MONTH(date) = MONTH('2016-01-18') 
AND YEAR(date) = YEAR('2016-01-18') 
GROUP BY text ORDER BY total DESC

Result : 结果:

a   2
b   2
c   2
d   1
e   1
f   1
g   1
h   1
i   1
x   1
y   1
z   1

My problem is, i only want to use top 5 data every hour, and want a result like this : 我的问题是,我只想每小时使用前5个数据,并且想要这样的结果:

data : 
a       18/01/2016 12:01        a       18/01/2016 13:01
b       18/01/2016 12:01        b       18/01/2016 13:01
c       18/01/2016 12:01        c       18/01/2016 13:01
d       18/01/2016 12:01        x       18/01/2016 13:01
e       18/01/2016 12:01        y       18/01/2016 13:01

result :
a   2
b   2
c   2
d   1
e   1
x   1
y   1

The query shown below will give the result required, 下面显示的查询将提供所需的结果,

SELECT text, max(date) as maxdate, COUNT(*) AS total 
FROM table 
WHERE 
DAY(date) = DAY('2016-01-18') 
AND MONTH(date) = MONTH('2016-01-18') 
AND YEAR(date) = YEAR('2016-01-18') 
GROUP BY text ORDER BY maxdate DESC

I hope this helps. 我希望这有帮助。

That is simple using Mysql Limit, you can use "LIMIT 5", in your case your code will be like 使用Mysql Limit很简单,可以使用“ LIMIT 5”,在这种情况下,您的代码将像

SELECT *, COUNT(*) AS total FROM table 
WHERE DAY(date) = DAY('2016-01-18') 
AND MONTH(date) = MONTH('2016-01-18') 
AND YEAR(date) = YEAR('2016-01-18') 
GROUP BY text ORDER BY total DESC LIMIT 5

it should return only top 5 results. 它应该只返回前5个结果。

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

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