mysql 【DATE_FORMAT】,【YEARWEEK】 統計每月,每週新增數值
mysql可根據create_time 欄位進行統計每月,每週新增資料,其中mysql 預設週日為每週的第一天,所以YEARWEEK函式要稍作改變。
表資料如下:
id name create_time update_time pid
1 a 2018-11-07 18:24:30
2 b 2018-11-01 18:24:44 1
3 c 2018-11-05 18:51:21 1
4 d 2018-10-03 18:25:15 1
5 e 2018-11-07 18:33:53 1
其中,pid是上級使用者id,表自身進行左連結查詢。SQL文如下:
SELECT COUNT(*) AS totalCount, COUNT(f.id) AS monthCount, COUNT(c.id) AS weekCount
FROM `customer` lc
LEFT JOIN customer f ON f.id = lc.`id` AND DATE_FORMAT(f.create_time ,'%y-%m') = DATE_FORMAT(NOW(),'%y-%m')
LEFT JOIN customer c ON c.id = lc.id AND YEARWEEK(c.create_time,1) = YEARWEEK(NOW(),1)
WHERE lc.pid = 1
其中YEARWEEK(NOW(),1),設定週一為每週的第一天,mysql預設週日為每週的第一天。
totalCount monthCount weekCount
4 3 2