トップページに戻る    次のSQLパズルへ    前のSQLパズルへ

8-28 末日と締日の問題

SQLパズル

DayTable
PKey  yyyymm  sime
----  ------  ----
   1  200802    20
   2  200802    27
   3  200802    28
   4  200802    29
   5  200802    30
   6  200802    31
   7  200804    29
   8  200804    30
   9  200804    31
  10  200805    29
  11  200805    30
  12  200805    31
  13  200902    28
  14  200902    29
  15  200902    30

yyyymmと締日で日付を作成するが、
締日がyyyymmの末日以降であれば、
末日とする。

出力結果
DayTable
PKey  yyyymm  sime  makeDay
----  ------  ----  ----------
   1  200802    20  2008-02-20
   2  200802    27  2008-02-27
   3  200802    28  2008-02-28
   4  200802    29  2008-02-29
   5  200802    30  2008-02-29
   6  200802    31  2008-02-29
   7  200804    29  2008-04-29
   8  200804    30  2008-04-30
   9  200804    31  2008-04-30
  10  200805    29  2008-05-29
  11  200805    30  2008-05-30
  12  200805    31  2008-05-31
  13  200902    28  2009-02-28
  14  200902    29  2009-02-28
  15  200902    30  2009-02-28


データ作成スクリプト

create table DayTable(PKey primary key,yyyymm,sime) as
select  1,'200802',20 from dual union
select  2,'200802',27 from dual union
select  3,'200802',28 from dual union
select  4,'200802',29 from dual union
select  5,'200802',30 from dual union
select  6,'200802',31 from dual union
select  7,'200804',29 from dual union
select  8,'200804',30 from dual union
select  9,'200804',31 from dual union
select 10,'200805',29 from dual union
select 11,'200805',30 from dual union
select 12,'200805',31 from dual union
select 13,'200902',28 from dual union
select 14,'200902',29 from dual union
select 15,'200902',30 from dual;


SQL

col makeDay for a20

select PKey,yyyymm,sime,
case when matubi < sime
     then to_char(to_date(yyyymm || '/' || to_char(matubi),'yyyymm/fmdd'),'yyyy-mm-dd')
     else to_char(to_date(yyyymm || '/' || to_char(sime)  ,'yyyymm/fmdd'),'yyyy-mm-dd')
     end as makeDay
from (select PKey,yyyymm,sime,
      extract(day from Last_day(to_date(yyyymm,'yyyymm'))) as matubi
      from DayTable)
order by PKey;


解説

Last_day関数で末日を求め、extract関数で日を取り出してます。
そして、末日と締日の大小関係で場合分けしてます。