TSQL Dynamic Pivot

时间:2017-04-14 15:10:34

标签: sql sql-server tsql

我有一个"小" PIVOT SQL脚本的问题。我已将此当前解决方案基于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,由于一些奇怪的原因,它不输出任何内容,但生成模式的所有代码都在那里

1 个答案:

答案 0 :(得分: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