1
2

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 5 years have passed since last update.

TIMESTAMP型のカラムから年・月別の集計をする

Posted at

目的

  • TIMESTAMP型で扱っている売上やユーザー登録のデータを、一度のSQL文の実行で年・月別の集計をしたい時のために。

ケース

  • テーブル:salesに、カラム:amount(売上)およびcreated_atが存在する場合。

対応

  • 演算子やBETWEENで抽出してもいいが、EXTRACTを使うとスッキリする。

select
    extract(year from created_at) as yyyy,
    extract(month from created_at) as mm,
    sum(amount) as total_amount
from
    sales
group by
    yyyy,
    mm
order by
    total_amount desc
;
  • いい感じに"YYYY", "MM"別で"total_amount"が表示される。
1
2
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
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?