ITPub博客

首页 > Linux操作系统 > Linux操作系统 > 滑动订单问题

滑动订单问题

原创 Linux操作系统 作者:壹頁書 时间:2013-11-19 23:22:06 0 删除 编辑
MySQL技术内幕148页

订单表有两个字段,订单日期(按月)和订单数量,需要求每个月到一年以后间隔的订单总数。
  1. create table MonthlyOrders
  2. (
  3.     ordermonth date,
  4.     ordernum int,
  5.     primary key (ordermonth)
  6. );

  7. insert into MonthlyOrders select add_months(to_date('2010-02-01','yyyy-mm-dd'),rownum),rownum from dual connect by level<=24;
  8. commit;

  9. SQL> select * from monthlyorders;

  10. ORDERMONTH ORDERNUM
  11. -------------- ----------
  12. 01-3月 -10 1
  13. 01-4月 -10 2
  14. 01-5月 -10 3
  15. 01-6月 -10 4
  16. 01-7月 -10 5
  17. 01-8月 -10 6
  18. 01-9月 -10 7
  19. 01-10月-10 8
  20. 01-11月-10 9
  21. 01-12月-10 10
  22. 01-1月 -11 11
  23. 01-2月 -11 12
  24. 01-3月 -11 13
  25. 01-4月 -11 14
  26. 01-5月 -11 15
  27. 01-6月 -11 16
  28. 01-7月 -11 17
  29. 01-8月 -11 18
  30. 01-9月 -11 19
  31. 01-10月-11 20
  32. 01-11月-11 21
  33. 01-12月-11 22
  34. 01-1月 -12 23
  35. 01-2月 -12 24

  36. 已选择24行。
作者的解决过程如下
1.求开始和结束的范围
2.用范围和订单表做不等连接
  1. select
  2. a.ordermonth frommonth,
  3. b.ordermonth tomonth,
  4. sum(c.ordernum) orders
  5. from    
  6.     MonthlyOrders a
  7.     inner join MonthlyOrders b
  8.         on add_months(a.ordermonth,11)=b.ordermonth
  9.     inner join MonthlyOrders c
  10.         on c.ordermonth between a.ordermonth and b.ordermonth
  11. group by a.ordermonth,b.ordermonth;
中间过程的结果如下

  1. SQL> select
  2.   2 to_char(a.ordermonth,'yyyy-mm-dd') frommonth,
  3.   3 to_char(b.ordermonth,'yyyy-mm-dd') tomonth
  4.   4 from
  5.   5 MonthlyOrders a
  6.   6 inner join MonthlyOrders b
  7.   7 on add_months(a.ordermonth,11)=b.ordermonth;

  8. FROMMONTH TOMONTH
  9. ---------- ----------
  10. 2010-03-01 2011-02-01
  11. 2010-04-01 2011-03-01
  12. 2010-05-01 2011-04-01
  13. 2010-06-01 2011-05-01
  14. 2010-07-01 2011-06-01
  15. 2010-08-01 2011-07-01
  16. 2010-09-01 2011-08-01
  17. 2010-10-01 2011-09-01
  18. 2010-11-01 2011-10-01
  19. 2010-12-01 2011-11-01
  20. 2011-01-01 2011-12-01
  21. 2011-02-01 2012-01-01
  22. 2011-03-01 2012-02-01

  23. 已选择13行。

来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-777038/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: Bad Habits
请登录后发表评论 登录
全部评论

注册时间:2013-10-19

  • 博文量
    620
  • 访问量
    6339833