簡體   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