LoginSignup
0
0

More than 1 year has passed since last update.

Tableau Tips:年齢計算

Last updated at Posted at 2023-03-01
  • datediff("year", [生年月日], today()) だけでOKかと思ったらダメだった。
    • 両日付を"year"でtruncateしたもの同士を比べてる、みたいな動き。
      • 生年月日: 2022-12-31 -(truncate)→ 2022-01-01
      • Today() : 2023-01-01 -(truncate)→ 2023-01-01
      • →結果:1 (year)←だめじゃん
  • 正しい計算式に修正したものの、次回また年齢計算の式を書くときまでに多分忘れるのでメモ。

  • 計算フィールドの内容

     if
     	[生年月日] > today()
     then
     	null
     else
     	datediff("year", [生年月日], today())
     	-
     	int(
     	  dateadd(
     	      "year",
     	      datediff("year", [生年月日], today()),
     	      [生年月日]
     	  ) > today()
     	)
     end
    

解説

  • datediff("year", [生年月日], today()) の部分は前述の通り
    • これを「YearDiff」と呼ぶことにする
  • 生年月日にYearDiffを足してみた結果が…
    • today()より大きい
      • →today()の年の誕生日をまだ迎えてない→年齢 = YearDiff - 1
    • today()以下
      • →today()の年の誕生日をもう迎えている→年齢 = YearDiff
  • dateadd( ... ) > today()は、true or falseが返ってくる
    • int( ... ) で数値に変換すると、1 or 0になる

テスト用データ

ages.csv
生年月日
2020/2/28
2020/2/29
2020/3/1
2020/3/2
2021/2/28
2021/3/1
2021/3/2
2022/2/28
2022/3/1
2022/3/2
2022/12/31
2023/2/28
2023/3/1
2023/3/2
2023/12/31

結果

  • スクリーンショット 2023-03-01 12.25.19.png
    • ちなみに上記のテストを行ったのは2023-03-01です…あしからず

雑感

  • 計算フィールド内で一時的に変数を使えたらいいのにな…
     $year_diff = datediff("year", [生年月日], today())
     
     if
     	[生年月日] > today()
     then
     	null
     else
     	$year_diff
     	-
     	int(dateadd("year", $year_diff, [生年月日]) > today())
     end
    
    • みたいな。

参考文献

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