我有表A
customerID Product
-------------------
101 A
101 B
102 B
102 C
想要将其转换为表格B,如:
customerID ProductA ProductB ProductC
---------------------------------------
101 1 1 0
102 0 1 1
我的最终目标是利用这个中间表来获得如下表C:
customerID Product_Combo
--------------------------
101 AB
102 BC
我想我知道如何将它从B改为C.但是如何从A到B呢?谢谢!假设我们在MS SQL中执行此操作,并且我们只有三个产品A,B和C.
答案 0 :(得分:0)
您可以将cursor用于customerId和此sql:
declare @Products varchar(10) = '';
--start cursor
set @Products = '';
SELECT @Products = @Products + [Product]
FROM [test].[dbo].[TableA]
WHERE customerId = @cursor
print @Products
--end cursor
答案 1 :(得分:0)
最简单的方法是使用案例:
q
结果
SELECT custId
,MAX(CASE WHEN product = 'A' THEN 1 ELSE 0 END) AS productA
,MAX(CASE WHEN product = 'B' THEN 1 ELSE 0 END) AS productB
,MAX(CASE WHEN product = 'C' THEN 1 ELSE 0 END) AS productC
FROM A
Group by custId
答案 2 :(得分:0)
你可以使用这样的查询进入B
SELECT
CustomerId,
CASE
WHEN [A] = 'A' THEN 1
ELSE 0
END AS ProductA,
CASE
WHEN [B] = 'B' THEN 1
ELSE 0
END AS ProductB,
CASE
WHEN [C] = 'C' THEN 1
ELSE 0
END AS ProductC
FROM #tableA
PIVOT (MAX(Product) FOR Product IN ([A], [B], [C])) AS p