SQL Server:在具有两列

时间:2018-03-13 03:37:53

标签: sql sql-server pivot

这是关于测试的问题。我有一个有两列的表。我想转向其中一个并输出另一个。

表格结构:

(Name varchar(10), Age int) 

我需要输出年龄值作为列和每个年龄值下面列出的名称。

从搜索开始,我只看到一些示例,其中至少有一个其他列用于" group by"因为想要更好的学期。换句话说,输出的每一行都有一个共同的因素。我的问题没有这个属性。

我试过了:

SELECT  
    [agevalue1], [agevalue2], [agevalue3], [agevalue4]
FROM
    (SELECT Name, Age FROM MyClass) AS SourceTable
PIVOT
    (MAX(Name)
       FOR Age IN ([agevalue1], [agevalue2], [agevalue3], [agevalue4])
    ) AS PivotTable;

我将agevalue *指定为字符串,即用引号括起来。我的列标题很好,但在它们下面有一排NULLS。

P.S。:该解决方案不需要使用枢轴,但我无法想到另一种方法。

示例数据:

  Name  Age

  Bob   11
  Rick  25
  Nina  30
  Sam   11
  Cora  16
  Rachel 25

期望的输出:

    11    16    25    30
  Bob  Cora  Rick    Nina
  Sam  NULL  Rachel  NULL

2 个答案:

答案 0 :(得分:0)

试试这个:

with tab as
(
Select 'A' Name, 10 Age union all
Select 'B',11 union all
Select 'c',10 union all
Select 'D',11 union all
Select 'E',11 union all
Select 'F',11 
)
select distinct
Age
, stuff((
    select ',' + g.Name 
    from tab g        
    where g.age = g1.age        
    order by g.age
    for xml path('')
        ),1,1,'') as Names_With_Same_Age
from tab g1
group by g1.age,Name

答案 1 :(得分:0)

将这些组合在一行:

11    16    25    30
 Bob  Cora  Rick    Nina

并将它们与另一组分开,例如:

11    16    25    30
Sam  NULL  Rachel  NULL

他们必须在每一行之间有不同的东西,因为做一个MAX(Name)只会为每个年龄提供一个名称。

此查询创建一个数字,用于将特定Age链接到行号,然后转动结果。正如您所说,PIVOT将按PIVOT函数中未引用的所有列进行分组,因此它将按此行索引器进行分组,将值分开,如您所愿。

;WITH IndexedClass AS
(
    SELECT
        M.Name,
        M.Age,
        -- The ordering will determine which person goes first for each Age
        RowIndexer = ROW_NUMBER() OVER (PARTITION BY M.Age ORDER BY M.Name) 
    FROM
        MyClass AS M
)
SELECT
    P.[11],
    P.[16],
    P.[25],
    P.[30]
FROM
    IndexedClass AS I
    PIVOT (
        MAX(I.Name) FOR I.Age IN ([11], [16], [25], [30])
    ) AS P