闲来无事,玩起Linux的cal命令,显示出某年某月的月历。尝试着用SQL语句写了一个类似的功能,有不完善的地方,请诸位大师指点!
查询某年某月的月历,输入字符串类型YYYYMM(比如'201102'表示2011年2月份):
- select max(decode(wk, 1, d)) Sun,
- max(decode(wk, 2, d)) Mon,
- max(decode(wk, 3, d)) Tue,
- max(decode(wk, 4, d)) Wed,
- max(decode(wk, 5, d)) Thu,
- max(decode(wk, 6, d)) Fri,
- max(decode(wk, 7, d)) Sat
- from (select to_char(rownum, '00') d,
- trunc((to_number(to_char(to_date('201109' || '01'), 'D')) + rownum - 2) / 7) p,
- to_char(to_date('201109' || '01') + rownum - 1, 'D') wk
- from dual
- connect by rownum <= to_number(to_char(last_day(to_date('201109' || '01')),'DD'))) t
- group by p
- order by 7;
查询某年的年历,输入字符串类型YYYY(比如'2008'表示2008年):
- select decode(row_number() over(partition by m order by p, m, 7),
- 1, decode (m,
- '01','Jan',
- '02','Feb',
- '03','Mar',
- '04','Apr',
- '05','May',
- '06','Jun',
- '07','Jul',
- '08','Aug',
- '09','Sep',
- '10','Oct',
- '11','Nov',
- '12','Dec')) as Mon,
- max(decode(wk, 1, d)) Sun,
- max(decode(wk, 2, d)) Mon,
- max(decode(wk, 3, d)) Tue,
- max(decode(wk, 4, d)) Wed,
- max(decode(wk, 5, d)) Thu,
- max(decode(wk, 6, d)) Fri,
- max(decode(wk, 7, d)) Sat
- from (select d,m,wk,
- trunc((p - 2 + row_number() over(partition by m order by d)) / 7) as p
- from (select to_char(to_date('2008' || '01' || '01') + rownum - 1, 'DD') d,
- to_char(to_date('2008' || '01' || '01') + rownum - 1, 'MM') m,
- to_char(trunc(to_date('2008' || '01' || '01') + rownum - 1, 'MM'), 'D') p,
- to_char(to_date('2008' || '01' || '01') + rownum - 1, 'D') wk
- from dual
- connect by to_date('2008' || '01' || '01') + rownum - 1 <
- to_date('2008' || '01' || '01') + interval '1' year) a) b
- group by m, p;
展示结果: