显示SQL Server数据透视表中的连锁字段

时间:2015-03-25 15:40:06

标签: sql-server concatenation pivot-table

我有一个以下结构的表格:

Title text
LineNo integer
Key   text
Value text
Units text

我创建了一个数据透视表,用于将行数据转换为列名:

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

有没有一种简单的方法可以做到这一点,而无需为单位创建单独的数据透视表并将两者连接在一起?

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

1 个答案:

答案 0 :(得分:0)

如果我理解你,我认为在源代码中进行连接可能会给你想要的结果:

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