我有这个表格,我想在其中计算每个客户 ID 的产品数量。 我有 3 个不同的product_id
我当前的表格如下所示:
客户_id | 产品_id |
---|---|
1 | 1001 |
1 | 1002 |
1 | 1003 |
2 | 1001 |
2 | 1003 |
3 | 1001 |
3 | 1002 |
4 | 1003 |
我想创建这个表格:
客户_id | 产品_id_1001 | 产品_id_1002 | 产品_id_1003 |
---|---|---|---|
1 | 1 | 1 | 1 |
2 | 1 | 0 | 1 |
3 | 1 | 1 | 0 |
4 | 0 | 0 | 1 |
可以吗?
这可以使用条件聚合来完成:
select Customer_id,
count(case when Product_id = 1001 then 1 end) as Product_id_1001,
count(case when Product_id = 1002 then 1 end) as Product_id_1002,
count(case when Product_id = 1003 then 1 end) as Product_id_1003
from mytable
group by Customer_id