SQL入門
最近SQLを使っているが,あまりに覚えられなくて苦労します。 そこで、忘備録を兼ねてよく使うものをまとめました。
バージョンはPostgres 10.5です。
テーブルの作成
- 何もないところから作る
create table hoge ( a varchar(255) , b smallint )
- データをselectして作る
create table hoge as select * from hogehoge;
条件分岐
- 等しいかをチェックする時
case a when b then hoge when c then hoge1 else hoge2 end
- 一般の場合
case when a = b then hoge when a < c then hoge2 else case when z > x then ggg when z = x then hhh end end
まとめたりする操作
- group byによる集約
select id , count(distinct a) , avg(b) from hoge group by id;
- parition byによる分割
idごとに時間ごとのscoreの累積和を取る.
select id ,sum(score) over(partition by id order by starte_at -- 範囲を指定する場合の例 rows between unbounded precedeing and 1 precedeing ) from hoge;
時間の操作
時間の型
- timestamp
- date
- time
- interval(時間の間隔)
さらにtimezoneの有無もある.
文字列を時間に
- timestamp型
select TO_TIMESTAMP('2000/01/01 20:15:00', 'YYYY/MM/DD HH24:MI:SS')
- date型
select TO_DATE('2000/01/01', 'YYYY/MM/DD')
フォーマットを合わせれば、形は多少自由でいける
時間を文字列に
select to_char(now(), 'YYYY-MM-DD HH:MM:SS')
時間から、年、月、日を取得
- date_trunc
- extract
SELECT DATE_TRUNC('month', current_timestamp + interval '1 month') + '-1 day';
時間の足し算、引き算
timestamp型の場合,
- timestamp型 - timestamp型
- timestamp型 + '1 month'
- timestamp型 - 数字はできなかった
time, date型
- 同じ型同士の演算
- time, date型 + interval'1 month'
多少慣れてきました. もう少し使いこなしたいものです.