416
365

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.

MySQL 日時ごとの集計まとめ

Last updated at Posted at 2015-02-01

月別、日別、時間別にレコード数を集計

一月毎

mysql> SELECT DATE_FORMAT(カラム1, '%Y-%m') AS time, COUNT(*) AS count FROM テーブル名 GROUP BY DATE_FORMAT(カラム1, '%Y%m');

一日毎

mysql> SELECT DATE_FORMAT(カラム1, '%Y-%m-%d') AS time, COUNT(*) AS count FROM テーブル名 GROUP BY DATE_FORMAT(カラム1, '%Y%m%d');

一時間毎

mysql> SELECT DATE_FORMAT(カラム1, '%Y-%m-%d %H:00:00') AS time, COUNT(*) AS count FROM テーブル名 GROUP BY DATE_FORMAT(カラム1, '%Y%m%d%H');

30分毎

mysql> SELECT FROM_UNIXTIME(TRUNCATE(UNIX_TIMESTAMP(カラム1) / 1800, 0) * 1800) AS time, COUNT(*) AS count FROM テーブル名 GROUP BY TRUNCATE(UNIX_TIMESTAMP(カラム1) / 1800, 0);

月別、日別、時間別にカラムの値の合計値を集計

一月毎

mysql> SELECT DATE_FORMAT(カラム1, '%Y-%m') AS time, SUM(合計値を求めるカラム) AS sum FROM テーブル名 GROUP BY DATE_FORMAT(カラム1, '%Y%m');

一日毎

mysql> SELECT DATE_FORMAT(カラム1, '%Y-%m-%d') AS time, SUM(合計値を求めるカラム) AS sum FROM テーブル名 GROUP BY DATE_FORMAT(カラム1, '%Y%m%d');

一時間毎

mysql> SELECT DATE_FORMAT(カラム1, '%Y-%m-%d %H:00:00') AS time, SUM(合計値を求めるカラム) AS sum FROM テーブル名 GROUP BY DATE_FORMAT(カラム1, '%Y%m%d%H');

30分毎

mysql> SELECT FROM_UNIXTIME(TRUNCATE(UNIX_TIMESTAMP(カラム1) / 1800, 0) * 1800) AS time, SUM(合計値を求めるカラム) FROM テーブル名 GROUP BY TRUNCATE(UNIX_TIMESTAMP(カラム1) / 1800, 0);

日付範囲指定でデータ集計

現在日時の現在の日付~1週間前までの集計(1日ごとのデータ集計)

mysql> SELECT DATE_FORMAT(カラム1, '%Y-%m-%d') AS time, SUM(合計値を求めるカラム) AS sum FROM テーブル名 WHERE カラム1 BETWEEN DATE_SUB(curdate(), interval 7 day) AND DATE_ADD(curdate(), interval 0 day) GROUP BY DATE_FORMAT(カラム1, '%Y%m%d');

現在日時の現在の日付~1週間前までの集計(30分ごとのデータ集計)

mysql> SELECT FROM_UNIXTIME(TRUNCATE(UNIX_TIMESTAMP(カラム1) / 1800, 0) * 1800) AS time, SUM(合計値を求めるカラム) AS sum FROM テーブル名 WHERE カラム1 BETWEEN DATE_SUB(curdate(), interval 7 day) AND DATE_ADD(curdate(), interval 0 day) GROUP BY TRUNCATE(UNIX_TIMESTAMP(カラム1) / 1800,0);

416
365
3

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
416
365

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?