|
题目:如果这个月第一个星期的天数 <=3天,那么这第一周要归为上一个月。
?
实现思路:
?
1.生成本年的所有日期和日期对应的月份,所在周
?
2.统计每个月份各周的天数
?
3.如果第一周的天数<=3天,那么月份-1
?
下面是实现的SQL脚本,相关的注释已在脚本里说明
?
/*生年初日期和年末日期*/
with x0 as
(select to_date('2015-01-01', 'yyyy-mm-dd') as 年初,
to_date('2015-12-31', 'yyyy-mm-dd') as 年末
from dual),
/*生成全年日期*/
x1 as
(select 年初 + level - 1 as 日期
from x0
connect by level <= (年末 - 年初) + 1),
/*计算日期所在的月份,所在周*/
x2 as
(
select 日期,
to_char(日期, 'mm') as 所在月份,
to_char(日期, 'iw') as 所在周,
to_number(to_char(日期, 'd')) 周几
from x1),
/*计算出每周是所在月份的第几周和对应天数*/
x3 as
(
select 日期,
所在月份,
所在周,
dense_rank() over(partition by 所在月份 order by 所在周) as 本月第几周,
count(*) over(partition by 所在月份, 所在周) 本周天数,
周几
from x2),
/*按题目规则,处理月份*/
x4 as
(
select 日期,
所在月份,
所在周,
本月第几周,
本周天数,
周几,
case
when 本月第几周 = 1 and 本周天数 <= 3 then
to_number(所在月份) - 1
else
to_number(所在月份)
end 名义月份
from x3)
select 名义月份 as 月份, min(日期) as 月初, max(日期) as 月末
from x4
group by 名义月份
order by 1

|