mysql按年月周日分组统计

骑驴找蚂蚁 · 2018年06月07日 · 阅读 623
$groupBy = '%Y%m%d'; //按日
if ($cycle == 'week') $groupBy = '%Y%u'; //按周
if ($cycle == 'month') $groupBy = '%Y%m'; //按月

$gameWhere = $gameId > 0 ? ' game_id = ' . $gameId . ' AND ': '';

$sql = <<<EOF
SELECT DATE_FORMAT(created_time, '$groupBy') AS `day`, COUNT(DISTINCT(uid)) AS person FROM `t1` 
WHERE $gameWhere created_time >= :startTime AND created_time <= :endTime GROUP BY DATE_FORMAT(created_time, '$groupBy')
UNION
SELECT DATE_FORMAT(created_time, '$groupBy') AS `day`, COUNT(DISTINCT(uid)) AS person FROM `t2` 
WHERE $gameWhere created_time >= :startTime2 AND created_time <= :endTime2 GROUP BY DATE_FORMAT(created_time, '$groupBy')
EOF;

关于作者

全栈工程师

文章被阅读 106.9k
获赞 11