简体   繁体   English

在SQL中转置两列

[英]Transposing Two Columns in SQL

I'm very new to SQL. 我对SQL非常陌生。 I looked forever on this site for an answer to this, but I couldn't. 我一直在这个网站上寻找这个问题的答案,但我做不到。 I have data that looks like this: 我有看起来像这样的数据:

Code |  Name  
A    |  John  
A    |  Bob  
A    |  Chris  
B    |  James  
B    |  Jen  
B    |  Teddy  

I would like it to build a query that would result in this: 我希望它建立一个查询,将导致以下结果:

Code | Name | Name2 | Name3  
A    | John |  Bob  | Chris  
B    | James|  Jen  | Teddy

Any help would be greatly appreciated. 任何帮助将不胜感激。

The solution is to use PIVOT . 解决方案是使用PIVOT However, a PIVOT is intended to be used on 'category' values, meaning you have the same set of categories per group. 但是, PIVOT旨在用于“类别”值,这意味着每个组具有相同的类别集。 You don't have anything that is similar between each group, like a 'name index' or anything. 每个组之间没有类似的东西,例如“名称索引”或其他任何东西。 So you can't identify the PIVOT columns properly. 因此,您无法正确识别PIVOT列。

The simple solution is to manufacture a category for each name in the group, like Name1 , Name2 , Name3 , etc. that you can PIVOT on. 简单的解决办法是制造每个名称类别组中,比如Name1Name2Name3 ,等等,你可以PIVOT上。 This can be done with a ROW_NUMBER() clause like this: 可以使用ROW_NUMBER()子句来完成,如下所示:

select Code,
  'Name' + cast(
      row_number() over (partition by Code order by code)
  as varchar(10)) as NameType,
  Name
from table1

Which produces results that look like this: 产生的结果如下所示:

| CODE | NAMETYPE |  NAME |
|------|----------|-------|
|    A |    Name1 |  John |
|    A |    Name2 |   Bob |
|    A |    Name3 | Chris |
|    B |    Name1 | James |
|    B |    Name2 |   Jen |
|    B |    Name3 | Teddy |

Now you have something shared between groups to PIVOT on - the NAMETYPE column: 现在,您可以在NAMETYPE列的PIVOT群组之间共享一些东西:

select * from ( 
  select Code,
    'Name' + cast(
        row_number() over (partition by Code order by code)
    as varchar(10)) as NameType,
    Name
  from table1
) a
pivot ( max(Name) for [NameType] in ([Name1], [Name2], [Name3]) ) piv

This produces the desired results: 这将产生预期的结果:

| CODE | NAME1 | NAME2 | NAME3 |
|------|-------|-------|-------|
|    A |  John |   Bob | Chris |
|    B | James |   Jen | Teddy |

Demo: http://www.sqlfiddle.com/#!6/21499/7 演示: http : //www.sqlfiddle.com/#!6/21499/7

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

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