如何将值从1列分成2个计数大于1的单独列。不想将行值放在列名中

时间:2018-07-26 03:38:47

标签: sql sql-server

我有这种格式的数据

Cust_ID    Order_Bname
----------------------
  1          Samsung
  1          Apple
  1          pixel
  2          Apple
  3          pixel
  3          LG

我要以这种格式输出:

Cust_ID     Order_Bname1    order_Bname2    Order_Bname3
-----------------------------------------------------------
 1           Samsung            Apple         Pixel
 2           Apple              Null          Null
 3           Pixel              LG            null

基本上我想为每个客户提供一行。

我已经尝试过FOR XML PATH

SELECT Cust_ID + ',' + Order_Bname 
FROM temp1
FOR XML PATH ('')

这将以这种格式返回输出

Cust_ID      Order
---------------------------------
 1           Apple,Samsung,Pixel
 2           apple
 3           pixel,LG

有没有办法做到这一点?我无法弄清楚

更新2:

WITH CTE_count
as
(
  select Customer_ID as ID,Brand_Name +'-'+ cast([Sale_Amount] as nvarchar) 
  as 
  brandname,ROW_NUMBER() OVER (PARTITION BY Customer_ID ORDER BY Customer_ID)
  AS lineNumber
  from dbo.sheet1
  group by Customer_ID,Brand_Name,[Sale_Amount]
)
 SELECT ID, brandname,lineNumber
 FROM CTE_count

使用此格式,我得到以下格式:

enter image description here

现在如何从行号动态创建列并将品牌名称放入其中

0 个答案:

没有答案