我的表看起来像这样:
CITY TOPIC RANK
NY FOOTBALL 1
NY BASKETBALL 2
....
NY BASEBALL 10
WS FOOTBALL 1
....
我想要的是:
CITY TOP 1 TOP 2 ... TOP 10
NY FOOTBALL BASKETBALL ... BASEBALL
WS FOOTBALL ............................
我该怎么做?非常感谢你!
答案 0 :(得分:0)
MySQL中没有直接的Pivot。 您需要在Query中手动创建列。 例如
select City,
max(case when Rank=1 then TopiC end) as Top1,
max(case when Rank=2 then Topic end) as Top2,
.
.
.
max(case when Rank=10 then Topic end) as Top10
from Table group by City
答案 1 :(得分:0)
你可以尝试
SELECT * FROM
(
SELECT City,Topic,
'Top '+ cast(Rank as varchar(10)) AS TopRank
FROM TableName
) T
PIVOT
(
max(topic)
FOR TopRank IN ([Top 1], [Top 2],[Top 10])
) as pvt
答案 2 :(得分:0)
我只想使用条件聚合:
select city,
max(case when rank = 1 then topic end) as top_1,
max(case when rank = 2 then topic end) as top_2,
. . .
max(case when rank = 10 then topic end) as top_10
from t
group by city;
这假设rank
没有联系。如果您有联系,则可能更喜欢listagg()
而不是max()
。