Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 将行值转换为列值_Sql_Sql Server_Tsql - Fatal编程技术网

Sql 将行值转换为列值

Sql 将行值转换为列值,sql,sql-server,tsql,Sql,Sql Server,Tsql,我有一张像下面这样的桌子 select * from table1 id name Address 1 John India 1 John USA 1 John Spain 2 Tom UK 2 Tom Ecuador 2 Tom Australia id name Address1 Address2 Address3 1 John India USA Spain 2 Tom

我有一张像下面这样的桌子

select * from table1

id  name    Address
1   John    India
1   John    USA
1   John    Spain
2   Tom UK
2   Tom Ecuador
2   Tom Australia
id   name    Address1   Address2    Address3
1    John     India       USA        Spain
2    Tom       UK       Ecuador      Australia
我希望输出如下所示

select * from table1

id  name    Address
1   John    India
1   John    USA
1   John    Spain
2   Tom UK
2   Tom Ecuador
2   Tom Australia
id   name    Address1   Address2    Address3
1    John     India       USA        Spain
2    Tom       UK       Ecuador      Australia

您可以使用
行编号()
和条件聚合:

select id, name,
       max(case when seqnum = 1 then address end) as address1,
       max(case when seqnum = 2 then address end) as address2,
       max(case when seqnum = 3 then address end) as address3
from (select t.*,
             row_number() over (partition by id, name order by (select null)) as seqnum
      from table1 t
     ) t
group by id, name;

. . 我根据标题更改了数据库标记。请标记您真正使用的数据库。谢谢戈登。这对我帮助很大lot@ali在这种情况下,请考虑接受并投票回答这个问题。