简体   繁体   English

是否在SQL Server Management Studio 2016中旋转并添加新列?

[英]Pivoting and adding new column in SQL Server Management Studio 2016?

I have a database that looks like this: 我有一个看起来像这样的数据库:

IndexID QuestionID  AnswerGiven
1       3           Phone
1       7           Strongly Agree
2       8           Agree
2       5           Yes
2       3           Chat
3       6           NULL
3       3           Phone
4       3           Web
4       7           Disagree

And I want to write a script to essentially pull out Question #3 into its own column called ContactChannel, like this: 我想编写一个脚本,将问题3实质性地拉入其自己的名为ContactChannel的列中,如下所示:

IndexID QuestionID  ContactChannel  AnswerGiven
1       7           Phone           Strongly Agree
2       8           Chat            Agree
2       5           Chat            Yes
3       6           Phone           Disagree
4       7           Web             Disagree

I'm new to SQL, but I suspect this has something to do with pivoting and sub-queries, and I know it can vary by database Any ideas for SSMS 2016? 我是SQL的新手,但我怀疑这与数据透视和子查询有关,并且我知道它可能因数据库而异SSMS 2016的任何想法?

You can use a query like the following: 您可以使用如下查询:

SELECT t1.IndexID, t1.QuestionID, t2.AnswerGiven AS ContactChannel, t1.AnswerGiven
FROM mytable AS t1
LEFT JOIN mytable AS t2 ON t1.IndexID = t2.IndexID AND t2.QuestionID = 3
WHERE t1.QuestionID <> 3;

The query is in ANSI SQL and should work in any RBDMS. 该查询使用ANSI SQL,并且可以在任何RBDMS中使用。

Demo here 在这里演示

You can use max window function to do this, assuming there is one row per questionid=3 per indexid. 您可以使用max window函数来执行此操作,假设每个questionid = 1行,每个indexid 3行。

select * from (
select indexid,questionid,
max(case when questionid=3 then answergiven end) over(partition by indexid) as contactchannel,
answergiven
from tbl
) t
where questionid<>3

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM