目前正在解决一个具有挑战性的问题,我一直在尝试解决我面临但无法解决的问题。非常感谢您的专业知识。
问题是:
旋转职业中的职业列,以便每个姓名按字母顺序排序并显示在其相应的职业下方。输出列标题应分别为 Doctor、Professor、Singer 和 Actor。
我的解决方案
SELECT
[Doctor],
[Professor],
[Singer],
[Actor]
FROM
(SELECT
ROW_NUMBER() OVER (PARTITION BY Occupation ORDER BY Name) ma,
[Name],
[Occupations]
FROM
Occupation
) AS source
PIVOT
( MAX([Name]) FOR [occupation] IN ([Doctor],[Professor],[Singer],[Actor]) ) as pv
ORDER BY ma
错误信息
ERROR 1064 (42000) at line 5: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '[Doctor],
[Professor],
[Singer],
[Actor]
FROM
(SELECT
' at line 2
等待您的回复。谢谢
最佳答案
Mysql
不支持PIVOT
操作符
使用条件聚合
来转换数据。
由于名称分为 4 个不同的列,因此在旋转数据后按名称排序没有多大意义。
select
Occupations,
max(case when occupation = 'Doctor' then name end) as Doctor,
max(case when occupation = 'Professor' then name end) as Professor,
max(case when occupation = 'Singer' then name end) as Singer,
max(case when occupation = 'Actor' then name end) as Actor
from Occupation
Group by Occupations
此外,您应该使用反引号 ``
而不是方括号 []
关于mysql - 在 SQL 中使用 Pivot 时的错误代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36511856/