首页 > 解决方案 > 在 SQL 中,如何按用户拥有的项目数对用户进行细分?(红移)

问题描述

如果这实际上真的很简单,我不是 SQL 专家,所以很抱歉。

我有一张表格,列出了用户和他们采取的不同问卷。用户可以按任何顺序进行问卷调查,并且可以根据需要获取任意数量的问卷。总共有 7 个可用,我想了解有多少个从 7 个中取出 1 个、7 个中的 2 个、7 个中的 3 个等

因此,一个非常粗略的示例是该表可能如下所示:

表格截图

我想要一个向我展示的查询:

count Users with 1 Q: 1
count Users with 2 Q: 2
count Users with 3 Q: 0
count Users with 4 Q: 0
count Users with 5 Q: 1
count Users with 6 Q: 0
count Users with 7 Q: 0

标签: sqlamazon-redshift

解决方案


假设您user_id在每一行都有,挑战是获得零值。Redshift 在创建表时不是很灵活。假设您的源数据有足够的行,您可以使用:

select n.n, coalesce(u.cnt, 0)
from (select row_number() over () as n
      from t
      limit 7
     ) n left join
     (select user_id, count(*) as cnt
      from t
      group by user_id
     ) u
     on n.n = u.cnt;

推荐阅读