繁体   English   中英

SQL - 查找 2020 年 2 月购买的用户百分比

[英]SQL - Find % of users who made purchase in Feb 2020

我有 2 个表:

Table A: User (users who made purchase) - user_id, date, product_id
Table B: Country - user_id, country

我想知道美国 2 月份购买的用户百分比

我认为下面的查询应该可以工作,但是我的朋友警告我它可能无法按预期工作(可能会得到额外的记录/行)。所以我只是想在这里与专家再次核实:)

select count(distinct b.user_id) / count(distinct a.user_id)
from country a
left join user b on a.user_id = b.user_id and date_trunc('month',date) = '2020-02-01' --don't worry about the date format
where a.country = 'US'

谢谢!

您可以使用条件聚合

select (count(distinct case when date_trunc('month',date) = '2020-02-01' then u.user_id) * 1.0 /
        count(distinct u.user_id)
       ) as ratio
from country c join
     user u
     on c.user_id = u.user_id a
where c.country = 'US'

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM