所以我有两个属性的表(见图)。现在我一直在尝试使用PIVOT完成我的任务,但没有成功。
我希望:
WorkOperationID
SparePartListID=1
WorkOperationsID
对应的所有SparePartsListID=2
。这可能实现吗?
答案 0 :(得分:0)
使用帮助或Row_Number()和一些动态SQL。这假设你想要 DENSE 列,否则删除 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 ...
编辑 - 如果你不想要DYNAMIC扩展[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