在初始表中枢转多个行

时间:2018-08-16 08:45:26

标签: sql tsql pivot

我有一张表格要显示以显示一个人所属的类别...

enter image description here

我想将其显示为:

enter image description here

成员和类别更多,但我认为理论应该是相同的。

我已经尝试过了,但是每个都只显示第一行。

预先感谢

2 个答案:

答案 0 :(得分:1)

@将,这就是您需要的逻辑。基本上是感兴趣列上的枢轴函数。

DECLARE @tbl TABLE (RegNo varchar(20), Category varchar(20), Number int)
INSERT INTO  @tbl
SELECT 'R1050162', 'Gym', 1 UNION ALL
SELECT 'R1050162', 'Personal Trainer', 1 UNION ALL
SELECT 'R0093126', 'Group Exercise', 1 UNION ALL
SELECT 'R0143614', 'Yoga Teacher', 1 


SELECT * 
    FROM
@tbl
PIVOT
(
SUM(Number)
FOR Category IN ([Gym], [Personal Trainer], [Group Exercise], [Yoga Teacher]

)
) AS PivotTable;

输出如下:

enter image description here

答案 1 :(得分:1)

您只需要对PIVOT函数中的Number字段求和,就可以获得多个类别的类别列表:

DECLARE @categories AS NVARCHAR(MAX),
    @your_query  AS NVARCHAR(MAX);

select @categories = STUFF((SELECT distinct ',' + QUOTENAME(Category) 
            FROM your_table 
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)') 
        ,1,1,'')

set @query = 'SELECT RegNo, ' + @categories + ' from 
            (
                SELECT RegNo, Category, Number FROM your_table) tab
                PIVOT
                (
                  SUM(Number) 
                 FOR Category IN (' + @categories + ')
            ) p iv
            ORDER BY piv.RegNo'

execute(@your_query)