Open1
Amazon Athenaで月末、月初のデータを取得するクエリ
基本知識
year, month, dayを組み合わせて特定の日付パーティションを取得する。
where
-- パーティションカラムを計算した結果でもパーティションを指定できます
-- 以下例はconcat関数で結合した結果が'20240624'であるパーティションが選択されます
concat(year, month, day) = '20240624'
月初、月末の取得
-- Athena 先月、今月
SELECT
date_trunc('month', current_timestamp) - interval '1' month AS "先月月初",
date_trunc('month', current_timestamp) - interval '1' day AS "先月月末",
date_trunc('month', current_timestamp) AS "今月月初",
date_trunc('month', current_timestamp) + interval '1' month - interval '1' day AS "今月月末"
;
月末のデータだけ取得
select
*
from
my_table
where
-- 月末のパーティションを指定します
-- その「パーティションの日付」と「そのパーティションの最終月の日付」が等しいパーティションを指定します
date_parse(concat(year, month, day), '%Y%m%d') = last_day_of_month(
date_parse(concat(year, month, day), '%Y%m%d')
)
月曜だけ取得する
select
*
from
my_table
where
-- 月曜日のパーティションを指定します
-- 曜日文字列を計算した結果が、'Monday'であるパーティションを指定します
date_format(
date_parse(concat(year, month, day), '%Y%m%d'),
'%W'
) = 'Monday'
今日を起点にNか月前の月の月初~月末のデータを取得する
SELECT
*
FROM
my_table
WHERE
concat(year, month, day)
BETWEEN
date_format(date_trunc('month', current_timestamp AT TIME ZONE 'Asia/Tokyo' - interval '2' month), '%Y%m%d') -- 今日から2か月前の月初
AND
date_format(last_day_of_month(current_timestamp AT TIME ZONE 'Asia/Tokyo' - interval '2' month), '%Y%m%d') -- 今日から2か月前の月末