2017-03-09 204 views
0

所以我有這個表的兩個屬性(見圖片)。現在我一直試圖使用PIVOT來完成我的任務,但沒有成功。基於另一列中的值將數據透視移動到列的行

我想有:

  • 在一行上所有WorkOperationIDSparePartListID=1
  • 所有WorkOperationsID對應於SparePartsListID=2在第2行。

這是可能實現?

enter image description here

+0

還有更多SparePartsList = 2比SparePartsList = 1 – McNets

+0

添加所需輸出的示例 – Stephen

回答

0

隨着幫助或ROW_NUMBER()和一些中對動態SQL。這是假設你想緻密列,否則刪除Partition By SparePartsListID(兩者)

Declare @SQL varchar(max) = Stuff((Select Distinct ',' + QuoteName(RN) From (Select Distinct RN=Row_Number() over (Partition By SparePartsListID Order by WorkOperationID) From YourTable) A Order by 1 For XML Path('')),1,1,'') 
Select @SQL = ' 
Select [SparePartsListID],' + @SQL + ' 
From (
     Select * 
       ,RN=Row_Number() over (Partition By SparePartsListID Order by WorkOperationID) 
     From YourTable 
    ) A 
Pivot (max(WorkOperationID) For [RN] in (' + @SQL + ')) p' 
Exec(@SQL); 

返回

SparePartsListID 1  2  3  4  ... 
1     101282 101344 101398 NULL ... 
2     84108 84921 85528 86228 ... 

編輯 - 如果你不想動態延伸[ 1],[2],[3],[4],...,[n]

Select * 
From (
     Select * 
       ,RN=Row_Number() over (Partition By SparePartsListID Order by WorkOperationID) 
     From YourTable 
    ) A 
Pivot (max(WorkOperationID) For [RN] in ([1],[2],[3],[4])) p 
相關問題