如何转置此表,以便我有两列,一列显示付费用户的比率,一列显示免费用户的比率。另外,在我的脚本中,有任何方法可以使代码更简洁,并且SQL'喜欢?我似乎无法在sqlfiddle中使用select语句创建表,因为我收到一条错误,说它只能在架构屏幕中创建。无论如何我可以将sql语句嵌入到新表中吗?
我在sqlfiddle上创建了一个脚本,可以为不同类型的用户计算一些下载指标:http://sqlfiddle.com/#!9/79bea4/1
答案 0 :(得分:1)
SELECT df.Date,
SUM(CASE WHEN ad.paying_customer = 'No'
THEN df.downloads ELSE 0 END) /
SUM(CASE WHEN ad.paying_customer = 'No' THEN 1 ELSE 0 END) AS `Average Downloads/Free User`,
SUM(CASE WHEN ad.paying_customer = 'Yes'
THEN df.downloads ELSE 0 END) /
SUM(CASE WHEN ad.paying_customer = 'Yes' THEN 1 ELSE 0 END) AS `Average Downloads/Paid User`
FROM
(
SELECT date,
user_id,
SUM(downloads) AS downloads
FROM download_facts
GROUP BY date,
user_id
) df
INNER JOIN user_dimension ud
ON df.user_id = ud.user_id
INNER JOIN account_dimension ad
ON ud.account_id = ad.account_id
GROUP BY df.Date
在这里演示:
答案 1 :(得分:1)
您可以通过获取下载总和并除以用户数来计算平均值。然后count(distinct)
可以获得每个组中的用户:
select df.date,
(sum(df.downloads) /
count(distinct case when ad.paying_customer = 'No' then df.user_id end)
) as avg_free,
(sum(df.downloads) /
count(distinct case when ad.paying_customer = 'Yes' then df.user_id end)
) as avg_paying
from download_facts df left join
user_dimension ud
on df.user_id = ud.user_id left join
account_dimension ad
on ad.account_id = ud.account_id
group by df.date;