SQL Server 2014将多个字符串行更改为列

时间:2018-02-17 15:22:32

标签: sql sql-server pivot

我有以下数据,它将有多个针对多种类型的标题。每个类型都有7个顶级游戏。

Genre | MarketingTitle 
------+----------------
Drama | Drama 1
Drama | Drama 2
...
Drama | Drama 7

我希望输出看起来像

Genre  | Title 1 | Title 2 | Title 3 | ... | Title7
-------+---------+---------+---------+-----+---------
Drama  | Drama1  | Drama2  | Drama3  | ... | Drama7
Comedy | Comedy1 | Comedy2 | Comedy3 | ... | Comedy7  

我尝试过数据透视表,但它只是不起作用

Select 
    GenreName, [Drama], [Comedy]
from
    (select 
         g.name as GenreName, p.MarketingTitle as MarketingTitle
     from 
         programme p
     inner join 
         Genre g on g.Id = p.GenreId
     where 
         topTitle = 1) c
pivot 
    (max(MarketingTitle) 
        for MarketingTitle in ([Drama], [Comedy])
    ) As pvt

所有内容都返回null,我很确定这个查询是错误的。

即使低于输出也是可取的,但我似乎无法使查询工作。任何帮助表示赞赏。

Drama   | Comedy  | ... | otherGenres
--------+---------+-----+------------
drama1  | comedy1 | ... |
drama2  | comedy2 | ... |
.. .
drama7  | comedy7 | ... |

1 个答案:

答案 0 :(得分:1)

尝试使用条件聚合

select
    GenreName, Title1 = max(case when rn = 1 then MarketingTitle end)
    , Title2 = max(case when rn = 2 then MarketingTitle end)
    , Title3 = max(case when rn = 3 then MarketingTitle end)
    , Title4 = max(case when rn = 4 then MarketingTitle end)
    , Title5 = max(case when rn = 5 then MarketingTitle end)
    , Title6 = max(case when rn = 6 then MarketingTitle end)
    , Title7 = max(case when rn = 7 then MarketingTitle end)
from (
    select g.name as GenreName, p.MarketingTitle as MarketingTitle
        , rn = row_number() over (partition by g.name order by p.MarketingTitle)
    from programme p
    inner join Genre g on g.Id = p.GenreId
    where top = 1
) t
group by GenreName