简体   繁体   English

TSQL动态数据透视

[英]TSQL Dynamic Pivot

I have a "small" issue with a PIVOT SQL script. 我对PIVOT SQL脚本有一个“小”问题。 I have based my current solution on a similar question here Dynamic PIVOT . 我目前的解决方案基于Dynamic PIVOT的类似问题。

I have managed to write the PIVOT script and largely it is ok. 我已经设法编写了PIVOT脚本,并且基本上可以。 However, my situation is this, instead of getting the unique entries onto single rows, the script outputs something like this 但是,我的情况是这样,脚本不会将唯一的条目放到单行中,而是输出如下内容

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

Whereas the results I am looking for should look something like this 而我正在寻找的结果应该看起来像这样

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

Here's the script 这是剧本

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

I'll be grateful for some pointers that can help me sort this out. 我将感谢一些可以帮助我解决这些问题的指针。 I've made a fiddle here which for some strange reason doesn't output anything but all the code to generate the schema is there 我在这里做了一个小提琴 ,由于某种奇怪的原因,它没有输出任何东西,但是所有用于生成模式的代码都在那里

Limit the fields in the PIVOT to only the required elements (X, Y, Value) 将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'

Returns 返回

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM