在SQL中透视表

时间:2018-04-25 14:07:15

标签: sql-server tsql pivot

我尝试接受原始查询并将其转移到SerOption列上,每个相应的SerOption下面都有Value列。因此,对于我的例子,我想要"资产标签,"制作","模型","描述"和"序列号"作为我的列标题,以及相应列中的每个[值]。

我的原始查询是:

SELECT s.SerOption, sv.value as [Value], sv.SerialCat, sv.item, [load]  
    FROM SerialValues SV JOIN [Serialization] S on S.OID = sv.SerialCat 
WHERE [load] in (141955) 
ORDER BY item, serialCat

到目前为止我在Pivoting的尝试是:

SELECT *
FROM (
    SELECT s.SerOption, sv.value as [Value], sv.SerialCat, sv.item, [load]  
        FROM SerialValues SV JOIN [Serialization] S on S.OID = sv.SerialCat 
    WHERE [load] in (141955) 
    ORDER BY item, serialCat
) AS serial
PIVOT
(
[Value] FOR s.SerOption in ('Asset Tag', 'Make', 'Model', 'Description', 'Serial Number')
) AS PVT

尝试运行时遇到的错误是: ORDER BY子句在视图,内联函数,派生表,子查询和公用表表达式中无效,除非还指定了TOP,OFFSET或FOR XML。 在' FOR'附近也会出现语法错误。关键字。

更新     我使用了以下更新的查询:

SELECT *
FROM (SELECT s.SerOption, sv.value as [Value], sv.SerialCat, sv.item, [load]  
FROM SerialValues SV JOIN
[Serialization] S
ON S.OID = sv.SerialCat 
WHERE [load] in (141955) 
) s
PIVOT (
MAX([Value]) FOR s.SerOption in ([Asset Tag], [Make], [Model], [Description], [Serial Number])
) AS PVT;

为了说明我现在得到的东西,当我通过Item订购PVT时,我得到以下内容(我知道我不需要订单,它只是为了表明我得到了单独的行值每个物品): enter image description here

2 个答案:

答案 0 :(得分:1)

我想你打算:

SELECT *
FROM (SELECT s.SerOption, sv.value as [Value], sv.SerialCat, sv.item, [load]  
      FROM SerialValues SV JOIN
           [Serialization] S
           ON S.OID = sv.SerialCat 
      WHERE [load] in (141955) 
     ) s
PIVOT (
    MAX([Value]) FOR s.SerOption in ([Asset Tag], [Make], [Model], [Description], [Serial Number])
) AS PVT;

目前还不清楚您想要哪种聚合功能。我选择MAX()为例。

答案 1 :(得分:0)

我明白了。我在外部选择中选择了我要查找的项目,并从内部选择中删除了sv.SerialCat。以下是获胜的查询。

SELECT [item], [load], [Asset Tag], [Make], [Model], [Description], [Serial Number]
FROM (SELECT s.SerOption, sv.value as [Value],  sv.item, [load]  
      FROM SerialValues SV JOIN [Serialization] S on S.OID = sv.SerialCat 
      WHERE [load] in (141955) 

     ) s
PIVOT (
    MAX([Value]) FOR s.SerOption in ([Asset Tag], [Make], [Model], [Description], [Serial Number])
) AS PVT