[[PostgreSQL]]

*概要 [#s03d204e]
SQLで月初と月末の日付を取得したい場合に使用できます。~ 
date_trunc関数で年、月、日の切り捨てが可能です。

*SQL [#q4ccc3ec]
***月初の取得 [#p29afc28]
 select date_current('month',now());

***月末の取得 [#o62e1a90]
 select date_current('month',now()) interval + '1 month' interval - '1 days';
 今月の1日を取得→1ヶ月先を取得→1日前を取得=今月の月末を取得
***月初から月末までの範囲の取得 [#x59ff8ce]
 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';

*応用 [#aa825cb0]
***範囲取得 [#j054bac9]
**先月のデータ [#ye359cb4]
 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日前の範囲を取得。

**今月のデータ [#z67b048f]
 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日から月末までの範囲を取得。

トップ   編集 差分 履歴 添付 複製 名前変更 リロード   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS