在 SQL 服务器数据透视 table 中显示串联字段

Displaying concatenated fields in a SQL Server pivot table

我有一个 table 结构如下:

Title text
LineNo integer
Key   text
Value text
Units text

我创建了一个数据透视表 table 来将行数据转换为列名:

SELECT * FROM
(SELECT Title, [Key],[Value] FROM Table1 WHERE [Key] LIKE 'Field_%' AND [LineNo]>0) as Data 
PIVOT(
MAX([Value])
FOR [Key] IN([Field_1],[Field_2],[Field_3])) As Piv

现在我想在每个值旁边显示单位。我尝试将它们连接起来,但这不起作用。

SELECT * FROM         
(SELECT     Title, [Key], [Value], [Units] FROM Table1                       
WHERE [Key] LIKE 'Field_%' AND [LineNo] > 0) AS Data 
PIVOT (MAX([Value]) + ' ' + [Units]) FOR [Key] IN ([Field_1],[Field_2],[Field_3])) AS Piv

有没有一种简单的方法可以做到这一点,而不必为单位创建单独的枢轴 table 并将两者连接在一起?

还有一些行没有单位所以如果单位是空白我不想显示它

如果我对你的理解是正确的,我认为在源代码中进行串联可能会给你想要的结果:

SELECT * FROM (
    SELECT Title, [Key], CONCAT([Value], ' ', Units) AS Value 
    FROM Table1 WHERE [Key] LIKE 'Field_%' AND [LineNo] > 0
    ) AS Data 
PIVOT(
MAX([Value])
FOR [Key] IN([Field_1],[Field_2],[Field_3])) AS Piv