sql - 如何在sql中进行转换和旋转
问题描述
我有一张如下表
我想计算每个产品并对其进行改造
t1
customer product
A a
A b
A c
B a
B c
C a
我想要的结果如下,
customer product(a) product(b) product(c)
A 1 1 1
B 1 0 1
C 1 0 0
有什么办法可以变身??
谢谢
解决方案
您可以使用conditional aggregation
select customer,count(case when product='a' then 1 end) as product_a,
count(case when product='b' then 1 end) as product_b,
count(case when product='c' then 1 end) as product_c
from tablename
group by customer
另一种选择可能是使用pivot operator
-
SELECT * FROM t
PIVOT (count(product) FOR product IN
( 'a' AS product_a, 'b' AS product_b, 'c' AS product_c ))
推荐阅读
- python - 使用while循环从函数返回变量
- mysql - The syntax of this MySQL logic?
- laravel-5 - 使用 swagger 在 laravel 中出现错误 419(未知状态)
- python - 使用 pymc3 对 MCMC 进行采样时,如何在可能性上添加 L1 正则化?
- web - 如何在 Weblogic 12.1.1 中导出数据源
- c - 如何使用 ## 运算符连接和评估宏
- php - PHP只更改ini文件中的一个值
- javascript - 分配给这个 javascript 工厂的参数是什么?
- batch-file - 如何将一行代码发送到另一个批处理文件中,该行中有一个特殊字符
- javascript - Identity.IsAuthenticated 在 ASP.Net Web API 中返回 false