LoginSignup
4
1

More than 5 years have passed since last update.

Prestoで日付チェックがしたいのだ

Posted at

やりたいこと

とある古いデータベースからEMBULKでデータをインポートした。型指定めんどいから全部STRINGで。
このテーブルに誕生日があるから、年齢のセグメントを作りたくて年齢算出しようとしたら苦労した話。

年齢の算出は

generation.sql
DATE_DIFF('year',date_parse(CONCAT(SUBSTR(birthday,1,4),'-',SUBSTR(birthday,5,2),'-',SUBSTR(birthday,7,2)),'%Y-%m-%d') ,localtimestamp)     

日付の形に無理やりして、timestampにparseしてlocaltimestampとyearでdiffをとる=年齢の完成

だが落ちまくる。

Query 20190605_115121_72231_4gcsi failed: Cannot parse "1935-04-00": Value 0 for dayOfMonth must be in the range [1,30]

1935年04月00日生まれがいる

ああもう困った。parseできないよー。
SQLの日付チェックといえばなんだっけなISDATE(string)

Function isdate not registered

はいおこられました。Prestoにはんなもんない。もううるう年計算含めてコーディングしてやるかーっておもったけどw
いいもん発見

PRESTOでの日付の妥当性チェックはTRY_CASTで

try_cast(value AS type) → type
Like cast(), but returns null if the cast fails.

https://prestodb.github.io/docs/current/functions/conversion.html
CAST失敗したらNULL返しまっせファンクション。

コレさえ見つかれば、そうですそういうことでした。

Try.sql
TRY_CAST(CONCAT(SUBSTR(birthday,1,4),'-',SUBSTR(birthday,5,2),'-',SUBSTR(birthday,7,2)) as date) is not null THEN
DATE_DIFF('year',date_parse(CONCAT(SUBSTR(birthday,1,4),'-',SUBSTR(birthday,5,2),'-',SUBSTR(birthday,7,2)),'%Y-%m-%d') ,localtimestamp)     

ちゃんと日付の妥当性チェックしてから処理ができるようになりました。
ちゃんちゃん。

4
1
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
4
1