SQL查询以确定一组发送1个或更多邀请的同类群组中的用户百分比

时间:2019-04-23 20:41:22

标签: mysql sql

我有下表:

USERS: id, created_at, onboarding_started_at
INVITATIONS: id, user_id

我正在编写一个查询,以显示发送1个或多个邀请的新用户的百分比。这是我到目前为止的内容:

SELECT floor(datediff(u.created_at, curdate()) / 7) AS weeks_ago,
       count(DISTINCT u.id) AS "New Users in Cohort", 
       count(DISTINCT i.id) AS "Total Invites in Cohort",
       count(DISTINCT i.user_id) AS "Uniq Users who invited Cohort",
count(DISTINCT u.id) / count(DISTINCT i.user_id) AS "% who invite"
FROM users u 
LEFT JOIN invitations i
     ON u.id = i.user_id
WHERE u.onboarding_started_at IS NOT NULL
GROUP BY weeks_ago;

当前,此输出错误地显示了“邀请的百分比”。示例数据:

weeks_ago | New Users in Cohort | Uniq Users who Invited Cohort | % who invite
-32 | 12 |  557 |  12 1.0000

在上面的示例中,% who invite显示1.0000

我该如何解决“邀请%的人”的问题? 我的Uniq Users who invited Cohort计算不正确吗?

谢谢

1 个答案:

答案 0 :(得分:1)

您是否尝试过将值强制转换为DECIMAL?

CAST(count(DISTINCT u.id)AS DECIMAL(7,2))/ CAST(count(DISTINCT i.user_id)AS DECIMAL(7,2))