用SQL实现年日历的方法

在很多论坛上见过要求使用SQL实现年日历例子,今天就自己动手写了,代码实现如下:

点击(此处)折叠或打开

  1. ----日历实现

  2. with test as
  3.  (select level as id_seq, trunc(sysdate, \'y\') + level - 1 as rq
  4.     from dual
  5.   connect by level <----得出一年的起止日期

  6.              add_months(trunc(sysdate, \'y\'), 12) - trunc(sysdate, \'y\') + 1),
  7. test1 as---穷举出一年的所有日期

  8.  (select id_seq, rq, to_char(rq, \'iw\') as iw, to_char(rq, \'mm\') as ---iw为一年当中的第几周

  9.     from test)
  10. select max(case to_char(rq, \'dy\')
  11.              when \'星期一\' then
  12.               to_char(rq, \'dd\')
  13.            end) as mon,
  14.        max(case to_char(rq, \'dy\')
  15.              when \'星期二\' then
  16.               to_char(rq, \'dd\')
  17.            end) as tus,
  18.        max(case to_char(rq, \'dy\')
  19.              when \'星期三\' then
  20.               to_char(rq, \'dd\')
  21.            end) as wen,
  22.        max(case to_char(rq, \'dy\')
  23.              when \'星期四\' then
  24.               to_char(rq, \'dd\')
  25.            end) as thur,
  26.        max(case to_char(rq, \'dy\')
  27.              when \'星期五\' then
  28.               to_char(rq, \'dd\')
  29.            end) as fri,
  30.        max(case to_char(rq, \'dy\')
  31.              when \'星期六\' then
  32.               to_char(rq, \'dd\')
  33.            end) as sta,
  34.        max(case to_char(rq, \'dy\')
  35.              when \'星期日\' then
  36.               to_char(rq, \'dd\')
  37.            end) as sun
  38.   from test1
  39.  group by im, iw
  40.  order by im, iw

实现的关键点:
1、获取到一年的起止日期
2、使用穷举法列出一年的所有日期
3、熟悉将日期转化成星期、第几周和获取月份的函数
4、根据月份、第几周分组排序即可

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

转载于:http://blog.itpub.net/29507357/viewspace-1208835/

你可能感兴趣的:(用SQL实现年日历的方法)