您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

SQL实现查找最近一周、一个月、三个月的数据_MySQL

2024/2/26 8:05:09发布13次查看
最近在做一个web项目,项目需求中需要提供查询订单表中最近一周,最近一个月,最近3个月的订单信息,以便运营人员进行数据分析。项目中使用的数据库使用的是mysql,所以以下所有命令都是基于mysql的。
首先来看看mysql的date_add函数:
date_add(date,interval expr unit), date_sub(date,interval expr unit)
these functions perform date arithmetic. the date argument specifies the starting date or datetime value. expris an expression specifying the interval value to be added or subtracted from the starting date. expr is a string; it may start with a “-” for negative intervals. unit is a keyword indicating the units in which the expression should be interpreted.
the interval keyword and the unit specifier are not case sensitive.
the following table shows the expected form of the expr argument for each unit value.
unit valueexpected expr format
microsecond microseconds
second seconds
minute minutes
hour hours
day days
week weeks
month months
quarter quarters
year years
second_microsecond 'seconds.microseconds'
minute_microsecond 'minutes:seconds.microseconds'
minute_second 'minutes:seconds'
hour_microsecond 'hours:minutes:seconds.microseconds'
hour_second 'hours:minutes:seconds'
hour_minute 'hours:minutes'
day_microsecond 'days hours:minutes:seconds.microseconds'
day_second 'days hours:minutes:seconds'
day_minute 'days hours:minutes'
day_hour 'days hours'
year_month 'years-months'
以上是摘自mysql官网的文档,链接:http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-add
用法如下:
当前时间:
mysql> select now();
+---------------------+
| now()               |
+---------------------+
| 2014-07-03 21:16:22 |
+---------------------+
1 row in set (0.00 sec)
下一个月:
mysql> select date_add(now(),interval 1 month);
+----------------------------------+
| date_add(now(),interval 1 month) |
+----------------------------------+
| 2014-08-03 21:16:28              |
+----------------------------------+
1 row in set (0.00 sec)
上一个月:
mysql> select date_add(now(),interval -1 month);
+-----------------------------------+
| date_add(now(),interval -1 month) |
+-----------------------------------+
| 2014-06-03 21:17:02               |
+-----------------------------------+
1 row in set (0.00 sec)
mysql>
项目中order表中的createtime是unix timestamp的,所以首先需要转换一下日期格式,这里用到了 from_unixtime(timestamp)。
最终的sql语句如下:
select from_unixtime(createtime) as datetime from wm_order having datetime between date_add(now(),interval -1 month) and now();
先到这里了,下班啦!
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product