SQL中PIVOT的新功能

时间:2017-01-24 15:16:11

标签: sql sql-server pivot sql-server-2000

我需要帮助才能找到以下内容是否可以实现

我有一张桌子,例如

enter image description here

是否可以使用PIVOT sql命令将其转换为类似的内容 如果是这样,有人可以帮助我。

enter image description here

3 个答案:

答案 0 :(得分:2)

没有UNPIVOT关键字,您必须手动进行此转换。

SELECT *
FROM (
    SELECT 
        [D].[UID]
        ,'Q1' AS [Question]
        ,[D].[Q1_Score] AS [Score]
        ,[D].[Category]
    FROM [DataSet] AS [D]
    UNION ALL
    SELECT 
        [D].[UID]
        ,'Q2' AS [Question]
        ,[D].[Q2_Score] AS [Score]
        ,[D].[Category]
    FROM [DataSet] AS [D]
    UNION ALL
    SELECT 
        [D].[UID]
        ,'Q3' AS [Question]
        ,[D].[Q3_Score] AS [Score]
        ,[D].[Category]
    FROM [DataSet] AS [D]
) [upivot]
ORDER BY
    [UID]
    ,[Question]

...如果您可以在UNPIVOT上使用新版本的SQL,那么您可以这样做......

SELECT 
    [UID]
    ,SUBSTRING([Question],1,2) AS [Question]
    ,[Score]
    ,[Category]
FROM [DataSet]
UNPIVOT (
    [Score] FOR [Question] IN (
        [Q1_Score]
        ,[Q2_Score]
        ,[Q3_Score]
    )
) [upivot]

上述任何一项的结果都是......

UID Question    Score   Category
1   Q1              10  Science
1   Q2              7   Science
1   Q3              5   Science
2   Q1              9   Maths
2   Q2              6   Maths
2   Q3              10  Maths
3   Q1              0   History
3   Q2              3   History
3   Q3              4   History
4   Q1              3   English
4   Q2              1   English
4   Q3              4   English

答案 1 :(得分:1)

您可以使用select with union创建一个新表。如果它需要是同一个表,那么您可以删除旧表并从新表创建它。

select unique_id,'Q1' as 'Question', Q1_score as 'Score', Category
from table
union all
select unique_id,'Q2' as 'Question', Q2_score as 'Score', Category
from table
union all
select unique_id,'Q3' as 'Question', Q3_score as 'Score', Category
from table
order by unique_id, Question

- 按照Matthew Whited的顺序将小组改为

答案 2 :(得分:0)

在我刚刚发布的这篇文章中,我证明了如上所示的复杂的UNION ALL SELECT-s是不必要的 - 如果你使用包含尽可能多的连续整数的内联表进行CROSS JOIN水平列取消枢轴。它适用于任何支持CROSS JOIN和CASE .. WHEN子句的数据库:

How to create multiple rows from a initial row

垂直旋转和"不旋转"意思是一样的。

在这里,我把它带到了极端:

Vertica - Is there LATERAL VIEW functionality?

在这篇文章中,我取消了两行表的转动,然后对转动的数据执行某些操作,然后重新转动它。

开心玩..