mysql - 在 SQL 中使用 Pivot 时的错误代码

标签 mysql sql

目前正在解决一个具有挑战性的问题,我一直在尝试解决我面临但无法解决的问题。非常感谢您的专业知识。

问题是:

旋转职业中的职业列,以便每个姓名按字母顺序排序并显示在其相应的职业下方。输出列标题应分别为 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/

相关文章:

mysql - 根据与另一个表的连接更新空白记录

mysql - 通过导致内存不足错误的列表在 Wicket 口表中加载数百万个数据库行

MYSQL WHERE 子句优化

sql - 从列值生成 Hive 行

sql - 根据最大值连接表

mysql - 如何对处于 "full line"模式 SQL 的数据进行分组和重新排列

SQL:如何找到从一个表链接到另一个表的最小条目数

mysql - 在 2 个或更多表上使用列名称作为结果标题

当我对 PHP 数组进行硬编码时,它与从 mysql 获取它时不一样

sql - 在 Odoo 的 SQL 查询中使用 ID 列表