日付ごとの集計

[MySQL]datetime型のデータから日付別の集計を行う

* 2006.04.01 Saturday
* 日記
* 04:53
* comments(0)
* trackbacks(0)
* by kokoromo

MySQLで日付時間データ入れておくデータ型、
datetime型はよく使いますよね。
データだけあって、日付別の集計が必要になってくることがありますよね。
普通に考えて集計やろうとするならgroup by使うんですが
このdatetime型、group by datetimeとやった場合、
秒あたりの重複数を数えてくれて日にち別の集計は行ってくれません。

そこで、substring関数。
substring(datetime,1,10) as date とやると group by でも使えます。


mysql> select id,board,dat,w,s,datetime from accesslog limit 100,1;
+--------+----------+------------+------+------+---------------------+
| id | board | dat | w | s | datetime |
+--------+----------+------------+------+------+---------------------+
| 220362 | gamenews | 1134178950 | NULL | NULL | 2005-12-11 15:58:35 |
+--------+----------+------------+------+------+---------------------+
1 row in set (0.27 sec)

こんなデータがあるとき、


mysql> select substring(datetime,1,10) as date,count(*) from
accesslog group by date;
+------------+----------+
| date | count(*) |
+------------+----------+
| 2005-11-23 | 4795 |
| 2005-11-24 | 8964 |
| 2005-11-25 | 8653 |
〜〜〜〜〜〜〜〜〜〜〜〜〜
| 2006-03-31 | 12785 |
| 2006-04-01 | 2405 |
+------------+----------+
130 rows in set (3 min 12.01 sec)



こうやってデータの日付別のデータ集計ができます。

                                                                                                                • -

MySQL4.1.1以上なら
date関数(datetime型のデータで日付を抜き出す関数)が使えますので、こちらを使ってください。速度が50分の1です。


mysql> select date(datetime) as date,count(*) from accesslog
group by date;
+------------+----------+
| date | count(*) |
+------------+----------+
| 2005-11-23 | 4795 |
| 2005-11-24 | 8964 |
| 2005-11-25 | 8653 |
〜〜〜〜〜〜〜〜〜〜〜〜〜
| 2006-03-31 | 12785 |
| 2006-04-01 | 2433 |
+------------+----------+
130 rows in set (5.08 sec)