LoginSignup
5
5

More than 5 years have passed since last update.

マイナンバーのチェックデジットを計算する(SQLで)

Posted at

マイナンバーの検査用数字(チェックデジット)

  • 11桁の数字 + 1桁の検査用数字 から成り立つ12桁の番号
  • その定義は総務省令第八十五号の第五条にある
  • 各プログラミング言語で計算するのが流行っているみたい

SQLでやってみた

demo

with
  -- 検査対象のマイナンバーテーブル
  t(mn) as (values
    ('123456789010'),
    ('123456789011'),
    ('123456789012'),
    ('123456789013'),
    ('123456789014'),
    ('123456789015'),
    ('123456789016'),
    ('123456789017'),
    ('123456789018'),
    ('123456789019')
  ),
  -- 11桁目から左方向への桁数(PostgreSQL以外の場合は別の方法で連番を作る必要あり)
  d (n) as (
    select generate_series(1, 11)
  ),
  -- Pn, Qn を計算する
  r (mn, pn, qn) as (
    select
      t.mn,
      cast(substr(t.mn, 12 - d.n, 1) as integer),
      case when d.n <= 6 then d.n + 1 when 7 <= d.n then d.n - 5 else null end
    from
      t,
      d
  ),
  -- Pn, Qn からチェックデジットを導出する
  c (mn, d) as (
    select
      r.mn,
      11 - (case when mod(sum(r.pn * r.qn), 11) <=1 then 0 else mod(sum(r.pn * r.qn), 11) end)
    from
      r
    group by
      r.mn
  )
select
  c.mn,
  -- 12桁目が正しいチェックデジットかどうか
  case when cast(substr(c.mn, 12) as integer) = c.d then 'true' else 'false' end as valid
from
  c
order by
  c.mn

結果

Kobito.rldPhE.png

他言語での実装

5
5
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
5
5