Mysql 求滑动订单问题
1.需求
求出滑动订单
2.示例
这里的滑动订单指的是,按照每12个月或者每个季度【3个月】求出订单的某个特征数。下面给出一个示例。
有表orders。表数据如下:
mysql> select * from orders;
+-------------+-----------+
| order_month | order_num |
+-------------+-----------+
| 2017-02-01 | 23 |
| 2017-03-01 | 26 |
| 2017-04-01 | 24 |
| 2017-05-01 | 27 |
| 2017-06-01 | 26 |
| 2017-07-01 | 32 |
| 2017-08-01 | 34 |
| 2017-09-01 | 30 |
| 2017-10-01 | 31 |
| 2017-11-01 | 32 |
| 2017-12-01 | 33 |
| 2018-01-01 | 31 |
| 2018-02-01 | 34 |
| 2018-03-01 | 34 |
| 2018-04-01 | 38 |
| 2018-05-01 | 39 |
| 2018-06-01 | 35 |
| 2018-07-01 | 49 |
| 2018-08-01 | 56 |
| 2018-09-01 | 55 |
+-------------+-----------+
20 rows in set (0.00 sec)
那么滑动订单问题就是指求出表中起始月份+12月的总订单数。
+-------------+------------+
| start_month | end_month |
+-------------+------------+
| 2017-02-01 | 2018-02-01 |
| 2017-03-01 | 2018-03-01 |
| 2017-04-01 | 2018-04-01 |
| 2017-05-01 | 2018-05-01 |
| 2017-06-01 | 2018-06-01 |
| 2017-07-01 | 2018-07-01 |
| 2017-08-01 | 2018-08-01 |
| 2017-09-01 | 2018-09-01 |
+-------------+------------+
8 rows in set (0.00 sec)
如上图所示就是分别求出 2017-02-01 => 2018-02-01
的总订单数;…2017-09-01 => 2018-09-01
的总订单数。最后的结果如下所示:
+-------------+------------+-------+
| start_month | end_month | total |
+-------------+------------+-------+
| 2017-02-01 | 2018-02-01 | 383 |
| 2017-03-01 | 2018-03-01 | 394 |
| 2017-04-01 | 2018-04-01 | 406 |
| 2017-05-01 | 2018-05-01 | 421 |
| 2017-06-01 | 2018-06-01 | 429 |
| 2017-07-01 | 2018-07-01 | 452 |
| 2017-08-01 | 2018-08-01 | 476 |
| 2017-09-01 | 2018-09-01 | 497 |
+-------------+------------+-------+
8 rows in set (0.00 sec)
3.代码一
select
t1.start_month
,t1.end_month
,sum(order_num) as total
from orders ord1
inner join
(
select
order_month as start_month
,date_add(order_month,interval 12 month) as end_month
from orders ord1
where date_add(ord1.order_month,interval 12 month) <= (select max(order_month) as max_month from orders)
)as t1
on ord1.order_month between t1.start_month and t1.end_month
group by t1.start_month;
这里有一点需要注意:在inner join...on
的语句中,on中的条件不一定非要是=号,可以使用>,<,!=,between on
等等.
3.代码二
select
date_format(a.order_month,'%Y%m') as start_month
,date_format(b.order_month,'%Y%m') as end_month
,sum(c.order_num) as total
from orders a
inner join orders b
on date_add(a.order_month,interval 12 month ) = b.order_month
inner join orders c
on c.order_month between a.order_month and b.order_month
group by a.order_month,b.order_month;
这个代码和上述的代码效果一样。