sql - 在 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
解决方案
假设您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;
推荐阅读
- reactjs - 如何在下一个 js 中设置和使用本地存储
- node.js - 列“PO->Ledger.id”必须出现在 GROUP BY 子句中或在聚合函数中使用
- php - 我和一些用户无法登录我的 Web 应用程序,我该如何解决?
- python - 使用 BeautifulSoup 解析谷歌新闻
- firebase - Firebase 模拟器 - 为 runtimeconfig.json 提供自定义名称/路径
- java - Java 中的 int[] arr[] 是什么意思?
- mongodb - 登录时强制注销
- php - 将购物车商品数据发送到 PayPal WooCommerce
- python - 为什么`zip`从第一个迭代器中又吃掉一个元素?
- javascript - 从 _id 字段生成一个唯一的 8 位数字 (MongoDB/Javascript)