2017-04-14 67 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对它有帮助 –