sql - 计算 postgres 中某个值的出现次数
问题描述
我有一张看起来像这样的桌子
email product_id
nen@something.com 20
nen@something.com 10
nen@something.com 20
nen@something.com 20
nen@something.com 10
我想创建一个表格视图来计算购买产品的次数(每封电子邮件)并将其显示在一行中。
email product_10 product_20
nen@something.com 2 3
我尝试使用以下 sql 执行此操作,但没有成功。
select email,count(product_id) from mytable group by email,product_id;
它给了我一张看起来像这样的桌子。
email count(product_id)
nen@something.com 2
nen@something.com 3
我在这里想念什么?如何将计数的产品放在一行中?
解决方案
用例当
select email, sum(case when productid=10 then 1 else 0 end) as
product_10,
sum(case when productid=20 then 1 else 0 end) as product_20
from mytable
group by email
推荐阅读
- java - 尽管使用了 android.util.Base64,但出现“找不到类“java.util.Base64””错误
- html - 打印网页时结果不同
- hive - 如何从配置单元中的元数据(Varchar)中提取数据?
- animation - 列表行平滑动画
- magento2 - 如何在 magento 2 中使用 REST API 获取所有类别而无需任何登录名或令牌?
- html - 我不断收到未捕获的错误:模板解析错误:意外的结束标记“div”。当标签已被另一个标签关闭时,可能会发生这种情况
- security - 为什么我面临移动网络的 ssl 问题?
- python - 将 fbprophet 作为 AWS Lambda 层导入
- mysql - 使用springboot从Mysql中获取数百万条数据
- sql - 如何将带有数据和边框的sql粘贴复制到记事本?