将行转置为列。 SQL Server(TSQL)中的2个Varchar列

enter image description here

将行转置为列。我在SQL Server(TSQL)中有2个Varchar列。

我无法使用数据透视,因为无法在varchar字段上运行聚合。我有2列,即。名称,职业。只需要转置那些。

评论
  • in_ut
    in_ut 回复

    您可以进行条件聚合:

    select max(case when occupation = 'Doctor' then name end) as Doctor,
           max(case when occupation = 'Actor' then name end) as Actor
    from (select t.*,  row_number() over (partition by occupation order by name) as grp
          from table t
         )
    group by grp;
    
  • 卡卡西
    卡卡西 回复

    您可以使用条件聚合。不清楚您想要什么,但也许:

    select name,
           sum(case when occupation = 'Dog Groomer' then 1 else 0 end) as num_dog_groomers,
           sum(case when occupation = 'Airline Mechanic' then 1 else 0 end) as num_airline_mechanics
           . . .
    from t
    group by name;