0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

date_diffで日付要素を加味して月数の差を求めたいときのメモ

Posted at

概要

date_diff関数は、2つの日付型に対して、指定した粒度での差を返す。
ただし、その際、指定した粒度より細かい要素は切り捨てる形で評価する。

そのため、日付間の月数を取りたいが日数が加味されない、年数を取る際に月数が加味されないといった性質が有り、実用上問題のある場合がある。

やり方

基準となる日付を切り捨て、その差分をもう一方の日付にも同様に差し引く。

select
    x, y,
    date_diff(y, x, month),
    date_diff(date_sub(y, interval date_diff(x, date_trunc(x, month), day) day), date_trunc(x, month), month)
from
    unnest([
        struct(date('2022-05-01') as x, date('2022-05-29') as y),
        struct(date('2022-05-01') as x, date('2022-06-01') as y),
        struct(date('2022-05-29') as x, date('2022-06-01') as y),
        struct(date('2022-05-29') as x, date('2022-06-01') as y),
        struct(date('2022-05-29') as x, date('2022-06-29') as y),
        struct(date('2022-05-29') as x, date('2022-06-30') as y)
    ])

スクリーンショット 2022-05-25 17.32.30.png

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?