构建一个PIVOT

时间:2012-05-04 19:25:49

标签: sql sql-server sql-server-2008 tsql pivot

我认为PIVOT会帮助我实现这一目标,但我无法开始任何事情。我今天有严重的SQL脑屁,我需要一些帮助。

这是我现在的输出:

Id    Name  Question    Answer
0     Test  Vault       A
0     Test  Container   1
1     Foo   Vault       B
1     Foo   Container   2

这是我想要的输出:

Id   Name Vault Container
0    Test A    1
1    Foo  B    2

可以这样做吗?

如果这不可能或非常复杂,我有另一种方法可以解决这个问题。我的备用查询的输出是:

Id   Name VaultId ContainerId
0    Test A       NULL
0    Test NULL       1
1    Foo  B       NULL  
1    Foo  NULL       2

在这里,我需要能够将每个Id / Name压缩成一行。我不记得怎么做其中任何一个!

3 个答案:

答案 0 :(得分:5)

DECLARE @Test TABLE
(
     Id      INT 
    ,[Name]VARCHAR(10) NOT NULL
    ,Question       VARCHAR(10) NOT NULL,
    Answer VARCHAR(10)

);  
INSERT  @Test   VALUES (0,'test1', 'vault','a');
INSERT  @Test   VALUES (0,'test1', 'Container ','1');
INSERT  @Test   VALUES (1,'test4', 'vault','b');
INSERT  @Test   VALUES (1,'test4', 'Container','2');



;WITH CTE
AS
(
    SELECT  t.id, t.[Name], t.[Question    ]   ,t.Answer
     FROM    @Test t
)

SELECT  * 
FROM    CTE
 PIVOT   ( max(answer) FOR Question     IN (vault,container) )  f;

enter image description here

答案 1 :(得分:2)

是的PIVOT是你需要的:)假设您的表名为MyPivot,请尝试:

SELECT Id, Name, [Vault], [Container]
FROM (SELECT Id, Name, Question, Answer FROM MyPivot) AS SourceTable
PIVOT (MAX(Answer) FOR Question in (Vault, Container)) as p;

编辑:要演示该语法的含义,请参阅以下细分:

PIVOT (<aggregate function>(<column being aggregated>) 
FOR <column that contains the values that will become column headers>
    IN ( [first pivoted column], [second pivoted column])

答案 2 :(得分:2)

你可以使用Static Pivot执行此操作:

create table temp
(
    id int,
    name varchar(10),
    question varchar(10),
    answer  varchar(10)
)

INSERT into temp   VALUES (0,'test', 'vault','a');
INSERT into temp   VALUES (0,'test', 'Container','1');
INSERT into temp   VALUES (1,'foo', 'vault','b');
INSERT into temp   VALUES (1,'foo', 'Container','2');

select *
from 
(
    select id, name, question, answer
    from temp
) x
pivot 
(
    max(answer)
    for question in ([container], [vault])
) p

drop table temp

或动态支点

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

select @cols = STUFF((SELECT distinct ',' + QUOTENAME(c.question) 
            FROM temp c
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT id, name, ' + @cols + ' from 
            (
                select id, name, question, answer
                from temp
           ) x
            pivot 
            (
                 max(answer)
                for question in (' + @cols + ')
            ) p '


execute(@query)

两者都会给你相同的结果:

enter image description here