在 SQL 中计算每年的事件数
我有一个有日期的事件列表。我试图在单个语句中使用简单的联接、选择等(无子查询)来计算 mySQL 中今年发生的事件数量,以及两侧 5 年发生的事件数量(无论是否发生任何事件)。
我有一张表,可以生成年份和当年的事件数量,但当该年没有发生事件时就会遇到问题
I have a list of events that have a date. I'm trying to count how many events take place in the current year, and 5 years on either side (regardless of whether any events took place) in mySQL using simple joins, selects, etc (no subqueries) in a single statement.
I have a table that produces the years and the number of events in that year, but am having problems when the year has no events taking place
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看 mysql 上的日期函数 http:// /dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_datediff
您可以使用 datediff 这会给您带来天数差异。前任;
其中abs(datediff(now(), event_date)) < 365*5
或 dateadd(),如果您的事件日期是时间戳,请使用 timestampdiff()
示例查询
UPDATE
基于我在这里读到的一些评论,这里有一个查询供您
随意调整5 in (365 * 5) for different range
UPDATE 2
这不是很漂亮,但你可以用纯mysql尝试这个。如果需要,您还可以将其修改为存储过程:
连接关闭后临时表将自行删除。如果在 SELECT 之后添加 DROP TABLE,则可能无法取回结果。
Look into date functions on mysql http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_datediff
You can use datediff which will give you difference in days. Ex;
WHERE abs(datediff(now(), event_date)) < 365*5
or dateadd(), if your event dates are timestamps, use timestampdiff()
Sample query
UPDATE
based on some of the comments I've read here, here's a query for you
Feel free to adjust 5 in (365 * 5) for different range
UPDATE 2
This is NOT very pretty but you can try this with pure mysql. You can also modify this to be a stored proc if necessary:
temporary table will get dropped by itself after your connection is closed. If you add DROP TABLE after SELECT, you might not get your results back.
您尝试过使用左连接吗?
修改:
通过此修改,您需要指向一个包含所有年份 (ONLY_YEARS) 的表,可能是一个包含从 1990 年到 2020 年的一列的虚拟表...
MySQL左连接优化链接
did you try to use join left?
MODIFIED:
With that modification, you need to point to a table that holds all the years (ONLY_YEARS), maybe a dummy table with one column that goes from 1990 to 2020...
Left join optimization for MySQL link
要选择两年之间发生的事件的计数(按年份分组),以下 sql 应该足够了:
但是,如果一年内没有发生任何事件,则不会返回任何结果。
数据库并不是真正为这种动态事物而设计的,我建议这种逻辑应该放在业务(或可能是数据访问)层中。
To select a count of events that happened between two years, grouped by years, the following sql should suffice:
However, if no events occurred in a year, no result will be returned for it.
Databases are not really designed for such dynamic things and I'd suggest such logic should be put in a business (or possibly data-access) layer.