好的,我有以下问题:
SELECT MIN(`date`), `player_name`
FROM `player_playtime`
GROUP BY `player_name`
然后我需要在以下查询中使用此结果:
SELECT DATE(`date`) , COUNT(DISTINCT `player_name`)
FROM `player_playtime /*Use previous query result here*/`
GROUP BY DATE( `date`) DESC LIMIT 60
我将如何做到这一点?
答案 0 :(得分:49)
您只需将第一个查询编写为子查询(派生表),在括号内,为其选择别名(下面为t
)并为列添加别名。
DISTINCT
也可以安全删除,因为内部GROUP BY
会使其变得多余:
SELECT DATE(`date`) AS `date` , COUNT(`player_name`) AS `player_count`
FROM (
SELECT MIN(`date`) AS `date`, `player_name`
FROM `player_playtime`
GROUP BY `player_name`
) AS t
GROUP BY DATE( `date`) DESC LIMIT 60 ;
由于COUNT
现在很明显只计算派生表的行数,因此您可以将其替换为COUNT(*)
并进一步简化查询:
SELECT t.date , COUNT(*) AS player_count
FROM (
SELECT DATE(MIN(`date`)) AS date
FROM player_playtime
GROUP BY player_name
) AS t
GROUP BY t.date DESC LIMIT 60 ;