获取当年和上个月的记录最后的
我对 mysql 很陌生,所以对不起,我需要获取 sellAt 列上个月的记录,因此例如有一个 sellAt 日期 yyyy-mm-dd 2022-05-12 我获取了其整个先前的记录月。我正在使用这个查询
SELECT at.*
from Analytics as at
where MONTH(at.SoldAtUpdatedAt) = MONTH(NOW() - INTERVAL 1 MONTH)
and YEAR(at.SoldAtUpdatedAt)= YEAR(NOW())
这个查询工作正常,我得到了当年上个月的结果,但是如果我的 sellAtUpdatedAt 的日期为 2022-01-01,即 2022 年 1 月 1 日,我想获取 2021 年 12 月记录怎么办. 如何查询这部分?我读到了有关 Datediff 的内容,但是当我获取时我得到 0 行..任何指导将不胜感激!我也尝试过( datepart 在 mysql 中不起作用) dateadd , datediff 但我得到零行...
I'm very new to mysql so excuse me, I need to get records of the last month of the soldAt column, so for e.g. there's a soldAt date yyyy-mm-dd 2022-05-12 I get the record for its whole previous month. I'm using this query
SELECT at.*
from Analytics as at
where MONTH(at.SoldAtUpdatedAt) = MONTH(NOW() - INTERVAL 1 MONTH)
and YEAR(at.SoldAtUpdatedAt)= YEAR(NOW())
This query works fine and i get previous month results for current year but what if my soldAtUpdatedAt has a date of 2022-01-01 i.e. 1st of january of 2022 i want to get the december month record for year 2021. How do i query this part? I read about Datediff but i get 0 rows when i fetch.. Any guidance would be appreciated!. Also I tried (datepart didnt work in mysql) dateadd , datediff but i get zero rows...
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
最佳查询是
DATE_FORMAT(date_value_or_expression, '%Y-%m-01')
创建日期月份第一天的日期(时间部分为零)。该表达式是常量,因此它只计算一次 - 不是在执行时计算,而是作为执行计划构建的一个步骤。此查询是 SARGable - 查询可以使用
SoldAtUpdatedAt
的索引。Optimal query is
DATE_FORMAT(date_value_or_expression, '%Y-%m-01')
creates the date for 1st day of date's month (with zero timepart). This expression is constant, hence it is calculated once - and not while execution but as a step of the execution plan building.This query is SARGable - the query may use the index by
SoldAtUpdatedAt
.此
WHERE
表达式可获取当前月份。这个让你得到一年前的同月。
因此,类似这样的内容应该可以让您了解这两个月的表格摘要。
LAST_DAY() 在这里对于月份计算和分组都很有用。它恰好可以在 MySQL 之外移植。
DATE_FORMAT(NOW(), '%Y-%m-01')
还可以获取当月的第一天。This
WHERE
expression gets you the current month.This one gets you the same month a year ago.
So, something like this should get you a summary of your table for those two months.
LAST_DAY() comes in handy here both for month computations and grouping. It happens to be portable outside MySQL.
DATE_FORMAT(NOW(), '%Y-%m-01')
also works to get the first day of the present month.