SQL 服务器使用 pivot/transpose
SQL Server using pivot/transpose
我需要 transpose/pivot 一个问题并寻找最佳方法:
原文:
ID
accountno
question
answer
1
111
How old are you?
15
2
111
What is your favorite color?
blue
最终结果:
ID
accountno
How old are you?
What is your favorite color?
1
111
15
blue
这是我的尝试:
--I only did the first question to see if it would work
select [ID],[accountno], [How old are you?]
from
(select ID,accountno,question,answer
from table
PIVOT
(max(answer)
For
question in ([How old are you?])
你们非常接近。看看下面
Select *
From (
Select accountno
,question
,answer
From YourTable
) src
Pivot ( max(answer) for question in ( [How old are you?]
,[What is your favorite color?]
) ) pvt
结果
我需要 transpose/pivot 一个问题并寻找最佳方法:
原文:
ID | accountno | question | answer |
---|---|---|---|
1 | 111 | How old are you? | 15 |
2 | 111 | What is your favorite color? | blue |
最终结果:
ID | accountno | How old are you? | What is your favorite color? |
---|---|---|---|
1 | 111 | 15 | blue |
这是我的尝试:
--I only did the first question to see if it would work
select [ID],[accountno], [How old are you?]
from
(select ID,accountno,question,answer
from table
PIVOT
(max(answer)
For
question in ([How old are you?])
你们非常接近。看看下面
Select *
From (
Select accountno
,question
,answer
From YourTable
) src
Pivot ( max(answer) for question in ( [How old are you?]
,[What is your favorite color?]
) ) pvt
结果