首页 > 解决方案 > 计算 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

我在这里想念什么?如何将计数的产品放在一行中?

标签: sqlpostgresql

解决方案


用例当

     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

推荐阅读