概要†SQLで月初と月末の日付を取得したい場合に使用できます。~ date_trunc関数で年、月、日の切り捨てが可能です。 SQL†月初の取得†select date_current('month',now()); 月末の取得†select date_current('month',now()) interval + '1 month' interval - '1 days'; 今月の1日を取得→1ヶ月先を取得→1日前を取得=今月の月末を取得 月初から月末までの範囲の取得†tableがpayment_tbl 月日データがtimestamp型で保存されているテーブルがp_dateだった場合 select * from payment_tbl where p_date between date_trunc('month',now()) and date_trunc('month',now()) + interval '1 month' - interval '1 days'; 応用†範囲取得†先月のデータ†select p_date,category_tbl.c_name,p_price from payment_tbl,category_tbl where payment_tbl.c_id=category_tbl.c_id and p_date between date_trunc('month',now()) - interval '1 month' and date_trunc('month',now()) - interval '1 days' order by p_date desc; betweenで本日から1ヶ月前の1日から今月の月初1日の1日前の範囲を取得。 今月のデータ†select p_date,category_tbl.c_name,p_price from payment_tbl,category_tbl where payment_tbl.c_id=category_tbl.c_id and p_date between date_trunc('month',now()) and date_trunc('month',now()) + interval '1 month' - interval '1 days' order by p_date desc; betweenで今月の1日から来月1日の1日前の範囲を取得。※今月の1日から月末までの範囲を取得。 |