我希望获取表格中前 5 名的项目,但在特定时间段内,例如 7 天。
这是表结构和一些随机示例数据
user_id | entry_id | sig | timestamp 1 1 8846 2015-03-27 20:49:56 1 2 8846 2015-03-27 20:49:56 1 3 8846 2015-03-27 20:49:56 1 4 4544 2015-03-27 20:49:56 1 5 4544 2015-03-27 20:49:56 1 6 65445 2015-03-27 20:49:56
User_id is unique, entry_id is primary key.
So for example I want to query the sig column to count the number of occurrences for each number within a time period of 7 days say 8846 appears 20 times.
This is the SQL query I have so far which counts the number of occurrences but not within a period of time. Its basic for the moment just need a working example.
SELECT sig, count(sig), sig_count FROM event
GROUP BY sig
ORDER BY sig_count
DESC LIMIT 5;
(编辑)其他详细信息
我之前错误地表述了这个问题。我真正想说的是,我需要根据过去 7 天内发生的情况获取前 5 个sig 并返回这些记录。这些数据将用于填充各种图表。
例如,如果我可以获得结果,然后使用 PHP,我可以获取entry_id 并循环它以获取时间戳和出现次数(频率“x”时间“y”)并将其弹出到图形。
我猜第一个查询会得到计数结果。然后可以运行第二个查询来获取该特定的 sig id 以及过去 7 天内关联的所有记录。
任何贡献将不胜感激。
最佳答案
据我了解您的问题,这是带有 where
子句的聚合:
select sig, count(*) as sig_count
from table t
where timestamp >= date_sub(now(), interval 7 day)
group by sig
order by sig_count desc
limit 5;
关于php - 根据 MySQL 数据库中的计数和日期获取前 5 个项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29335089/