MySQL将列转换为行

时间:2016-10-26 09:44:44

标签: mysql pivot unpivot

我试图弄清楚如何计算所有总裁,经理等,然后在一个查询中将列转换为行。 例如,有一些示例db' 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 )

1 个答案:

答案 0 :(得分:0)

您可以使用子查询来标准化职称,然后按案例陈述进行分组和排序,以按照陈旧性的降序生成输出。

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