LoginSignup
0
1

More than 3 years have passed since last update.

Sequelize(PostgreSQL)で月次の集計を行う

Posted at

例えば、特定の会社に所属するアカウントの新規作成数を月次で集計したい場合(そんな状況があるのかどうかはさておき)

想定結果

month cnt
2020-03 10

PostgreSQL

SELECT 
TO_CHAR(created_date, 'YYYY-mm') AS month,
COUNT(user_id) AS created_cnt
FROM users
WHERE company_id = 1 
GROUP BY month

Sequelize

const sequelize = require('sequelize');
const userCtrl = require('../models/userCtrl')
...
const res = await userCtrl.findAll({
  attributes: [
    [sequelize.fn('to_char', sequelize.col('created_date'), 'YYYY-mm'), 'month'],
    [sequelize.fn('count', sequelize.col('user_id')), 'created_cnt']
  ],
  where: {
    company_id: 1,
  },
  group: ['month'],
});

sequelize.fn...データベース関数を指定
sequelize.col...対象のカラムを指定

蛇足

MySQLではTO_CHAR関数の代わりにDATE_FORMAT関数を使う
指定するフォーマットには、「%」文字をつける

SELECT
DATE_FORMAT(created_date, '%Y-%m') AS month,
COUNT(user_id) AS created_cnt
...

参考

Sequelize公式 - sequelize.fn
MySQL5.6リファレンスマニュアル - DATE_FORMAT

0
1
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
0
1