AdSense

網頁

2018/2/24

MySQL 用日期來GROUP BY datetime欄位

MySQL如果只要以日期DATEGROUP BY DATETIME格式欄位而不考慮時間,可使用DATE()函式。

例如從下面score_board資料表查出不同測試者每一天的總分。

+---------+---------+--------+------------------------+
| test_id |  tester |  score |     test_date_time     |
+---------+---------+--------+------------------------+
|       1 |  matt   |     50 |  2018-01-02 09:30:00   |
|       2 |  john   |     84 |  2018-01-02 11:01:00   |
|       3 |  john   |     77 |  2018-01-02 12:10:00   |
|       4 |  john   |     88 |  2018-01-03 15:15:00   |
+---------+---------+--------+------------------------+

則可用以下語法查詢。

SELECT tester, SUM(score) daily_total_score, DATE(test_date_time) test_date 
FROM score_board
GROUP BY tester, DATE(test_date_time)
ORDER BY test_date;

查詢結果如下

+--------+-------------------+-------------+
| tester | daily_total_score |  test_date  |
+--------+-------------------+-------------+
| matt   |                50 |  2018-01-02 |
| john   |               161 |  2018-01-02 |
| john   |                88 |  2018-01-03 |
+--------+-------------------+-------------+

參考:

沒有留言:

AdSense