MySQL 将列转换为行

MySQL converting columns to rows

我想弄清楚如何计算所有总裁、经理等,然后在一个查询中将列转换为行。 例如这里有一些示例数据库 'employee':http://www.mysqltutorial.org/tryit/ 我可以使用这样的查询来计算所有类型的员工:

SELECT 
    SUM(CASE
        WHEN jobTitle = 'President' THEN 1
        ELSE 0
    END) AS 'Presidents',
    SUM(CASE
        WHEN jobTitle LIKE 'VP%' THEN 1
        ELSE 0
    END) AS 'VPs',
    SUM(CASE
        WHEN jobTitle LIKE '%Manager%' THEN 1
        ELSE 0
    END) AS 'Managers',
    SUM(CASE
       WHEN jobTitle LIKE '%Rep' THEN 1
       ELSE 0
    END) AS 'Reps'
FROM
employees;

但现在我想将列转换为行,但我不知道如何将其包含在类似于此处答案的查询中: Mysql Convert Column to row (Pivot table )

您可以使用子查询来标准化职位名称,然后使用 case 语句进行分组和排序,以按职位高低顺序生成输出。

select  jobtitle,count(*) from
(
SELECT  case 
        WHEN jobTitle = 'President' THEN 'Presidents'
        WHEN jobTitle LIKE 'VP%' THEN 'VPs'
        WHEN jobTitle LIKE '%Manager%' then 'Managers'
        WHEN jobTitle LIKE '%Rep' then 'Reps'
        end as Jobtitle
FROM
employees
 ) s

group   by Jobtitle
order by 
case when jobtitle = 'Presidents' then 1
 when jobtitle = 'VPs' then 2
 when jobtitle = 'Managers' then 3
 when jobtitle = 'Reps' then 4
 end