如何在SQL中将具有多个值的类别变量转换为几个二进制变量?

时间:2019-04-13 18:10:18

标签: sql pivot

给出一个具有多个值的字符变量(在我的示例product中),如何将其转换为几个二分变量,同时按另一个变量(在我的示例customer中)分组?

示例:如何从

转换数据
customer     product
custumerA    productA
customerA    productA
customerA    productC
customerA    productD
customerB    productB
customerB    productD
...

进入

customer      productA    productB   productC  productD  .... productZ
customerA     1           0          1         1              0
customerB     0           1          0         1              0

...

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:0)

假设您知道所需的产品,请使用汇总:

select customer,
       max(case when product = 'productA' then 1 else 0 end) as productA,
       max(case when product = 'productB' then 1 else 0 end) as productB,
       max(case when product = 'productC' then 1 else 0 end) as productC,
       max(case when product = 'productD' then 1 else 0 end) as productD
from t
group by customer;

如果您不知道产品列表,则需要动态SQL,具体如何执行取决于数据库。

答案 1 :(得分:0)

动态数据透视查询

Declare @sql nvarchar(max)

set @sql='select * from (select customer, product, count(product)Cnt from #mytable group by customer, product)tbl
          Pivot
         (sum(Cnt) for product In ('+stuff( (select distinct ', '+ product from #mytable for xml path('')),1,1,'')  +') ) as PivotTable'

 execute sp_executesql @sql

enter image description here