我正在撰写报告,我的数据如下:
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
获取文本总数:
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
结果:
a 2
b 2
c 2
d 1
e 1
f 1
g 1
h 1
i 1
x 1
y 1
z 1
我的问题是,我只想每小时使用前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
答案 0 :(得分:0)
下面显示的查询将给出所需的结果
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
我希望这会有所帮助。
答案 1 :(得分:0)
使用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
它应该只返回前5个结果。