此查询从活动表中获取每月所有活动玩家的数量:
SELECT
date_trunc('month', createdat) as month,
count(distinct playerid) as play_all
FROM
activity
group by month
order by 1
此查询获取每月玩“蜜蜂”游戏的玩家人数:
SELECT
date_trunc('month', createdat) as month,
count(distinct playerid) as play_bee
FROM
activity
where gamename = 'bee'
group by month
order by 1
我如何获得每月玩“蜜蜂”游戏的玩家百分比?
答案 0 :(得分:1)
这可能有效:
SELECT
DATE_TRUNC('month', createdat) AS month,
COUNT(DISTINCT playerid) AS play_all,
COUNT(DISTINCT CASE WHEN gamename = 'bee' THEN playerid END) AS play_bee,
100. * COUNT(DISTINCT CASE WHEN gamename = 'bee' THEN playerid END)
/ COUNT(DISTINCT playerid) AS percent_play_bee,
FROM
activity
group by month
order by 1
它利用以下事实:CASE WHEN gamename = 'bee' THEN playerid END
如果playerid
将返回gamename = 'bee
,但如果不是则将返回NONE
。 (我不确定NONE响应是否会包含在COUNT(DISTINCT..)
中,因此它可能会被1禁用。)
基本上,CASE
是针对每一行进行单独评估的。然后,将值设为DISTINCT,然后对其进行计数。