LoginSignup
0
0

More than 1 year has passed since last update.

Oracleで和暦一覧を取得するSQL

Posted at

はじめに

和暦の一覧を取得するSQLです。
SelectBox等のリストとして利用できるかと思います。
適当に組み替えてvalueの値等を追加してください。

確認動作環境

  • Oracle 11R2

SQL

with master as (
    -- 疑似的な和暦のマスターです。
    -- このままでも、テーブルでも。
    -- 明治が欲しい場合は追加してください。
    select 'T' as code, '大正' as name, to_date('19120730','yyyymmdd') as start_date, to_date('19261224','yyyymmdd') as end_date from dual
    union all
    select 'S', '昭和', to_date('19261225','yyyymmdd'), to_date('19890107','yyyymmdd') from dual
    union all
    select 'H', '平成', to_date('19890108','yyyymmdd'), to_date('20190430','yyyymmdd') from dual
    union all
    select 'R', '令和', to_date('20190501','yyyymmdd'), trunc(sysdate) from dual
),
list as (
    -- 大正の開始からSYSDATE時点までのレコードを取得します。
    select add_months(to_date('19120101','yyyymmdd'), (level - 1) * 12) as temp from dual connect by level <= to_number(to_char(sysdate, 'yyyy')) - 1912 + 1
)
select
    code
    , name
    , rank() over (partition by code order by temp) as japan_year -- 年号毎の年を取得。
    , to_char(temp, 'yyyy') as ad
    , start_date
    , end_date 
from
    list
    inner join master on
        to_char(list.temp, 'yyyy') between to_char(master.start_date,'yyyy') and to_char(master.end_date,'yyyy')
order by ad, start_date
; 

さいごに

利用にあたっては動作確認をお願いします。
『こうしたほうが良い』とかもあれば、ご教授ください。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0