2017-04-14 70 views
1

我有一個PIVOT SQL腳本的「小」問題。我已經基於我的當前解決方案在這裏類似的問題Dynamic PIVOTTSQL Dynamic Pivot

我設法寫了PIVOT腳本,很大程度上沒問題。然而,我的情況是這樣的,而不是得到的唯一入口到單個行,該腳本輸出這樣的事情

ListingEntryId Address  Employees Location 
1    NULL   NULL  Nottingham 
1    Canal Street NULL  NULL 
1    NULL   3   NULL 
2    NULL   NULL  London 
2    Camden   NULL  NULL 
2    NULL   12   NULL 

而處理結果我找了應該是這個樣子

ListingEntryId Address  Employees Location 
1    Canal Street 3   Nottingham 
2    Camden   12   London 

這裏的該腳本

DECLARE @listingId INT = 1; 
DECLARE @cols AS NVARCHAR(MAX), @query AS NVARCHAR(MAX) 

SELECT LEV.ListingColumnId, LEV.ListingEntryId, LE.CreatedBy, LEV.EntryValue, LD.ColumnTitle, LD.[Index] 
INTO #ListingTable 
FROM ListingEntryValue LEV LEFT OUTER JOIN 
ListingEntry LE ON LEV.ListingEntryId=LE.Id 
LEFT OUTER JOIN 
ListingDefinition LD ON LEV.ListingColumnId = LD.Id 
WHERE LE.ListingId = @listingId; 

SELECT * FROM #ListingTable; 

SELECT @cols = STUFF((SELECT DISTINCT TOP 100 PERCENT ',' + QUOTENAME(LT.ColumnTitle) FROM #ListingTable LT 
FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'), 1,1,'') 
SELECT @cols; 

SET @query = 'SELECT ListingEntryId,' + @cols + ' FROM (SELECT ListingEntryId, ListingColumnId, EntryValue, ColumnTitle, [Index] FROM #ListingTable LT) x 
PIVOT (MAX(EntryValue) FOR ColumnTitle IN (' + @cols + ') 
) p' 

PRINT @query 
EXECUTE(@query); 


DROP TABLE #ListingTable 

我會感謝一些指針,可以幫助我解決這個問題。我做了一個fiddle here這對於一些奇怪的原因不輸出任何東西,但所有的代碼來生成架構有

回答

2

限制在PIVOT的字段只需要的元素(X,Y,值)

SET @query = 'SELECT ListingEntryId,' + @cols + ' FROM (SELECT ListingEntryId, EntryValue, ColumnTitle FROM #ListingTable LT) x 
PIVOT (MAX(EntryValue) FOR ColumnTitle IN (' + @cols + ') 
) p' 

返回

ListingEntryId Address   Employees Location 
1    Canal Street 3   Nottingham 
2    Camden   12   London 
+0

感謝約翰,這個工作! –

+0

@ObiOnuorah對它有幫助 –