如何基于行号动态创建新列

时间:2018-07-26 05:40:30

标签: sql sql-server

我已经在我的表上创建了这样的查询:

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

现在如何为每个客户ID获得1行,如:

cust_id order1 order2 order3 order4 100000443 AMANA-71.31 AMANA-104.4 AMANA-109.89 AMANA-104.4

如何修改以上查询

我想对仅作为示例给出行的每个ID进行操作

2 个答案:

答案 0 :(得分:2)

使用Cte,做

...
Select cust_id,
  max(when lineNumber=1 then brandname end) order1,
  max(when lineNumber=2 then brandname end) order2,
  max(when lineNumber=3 then brandname end) order3,
  max(when lineNumber=4 then brandname end) order4
From Cte_count group by cust_id, brandname

答案 1 :(得分:0)

您需要编写动态数据透视查询才能获得结果。
参考链接:

Convert Rows to columns using 'Pivot' in SQL Server