如何在MySQL Pivot中动态添加列和按NULL分组?

时间:2019-02-27 02:56:48

标签: mysql

我有一个表,其中包含名称和职业的值。我正在尝试做两件事

  1. 旋转表(已实现)
  2. 根据值动态添加/删除列
  3. 减少数据透视后各列中的NULL值

我的查询:

select Actor, Teacher, Doctor from (
SELECT
(case when occupation = (select distinct occupation from occs a order by 1 limit 0,1) then name else NULL end) as "Actor"
,(case when occupation = (select distinct occupation from occs a order by 1 limit 1,1) then name else NULL end) as "Teacher"
,(case when occupation = (select distinct occupation from occs a order by 1 limit 2,1) then name else NULL end) as "Doctor"
FROM occs order by 1) x ;

以上查询的输出:

+-------+---------+--------+
| Actor | Teacher | Doctor |
+-------+---------+--------+
| NULL  | NULL    | ketty  |
| NULL  | Jane    | NULL   |
| NULL  | Zhan    | NULL   |
| julia | NULL    | NULL   |
| meera | NULL    | NULL   |
+-------+---------+--------+

我正在尝试将输出作为

+-------+---------+--------+
| Actor | Teacher | Doctor |
+-------+---------+--------+
| julia | Jane    | ketty  |
| meera | Zhan    | NULL   |
+-------+---------+--------+

另外在我的sql中,我指定了Actor,Teacher,Doctor列。 有没有一种方法可以扫描表并获取列,而无需手动进行区分。

DDL / DML解决问题:

CREATE TABLE occs (
  name varchar(10) DEFAULT NULL,
  occupation varchar(10));


insert into occs values ('julia','Actor');
insert into occs values ('meera','Actor');
insert into occs values ('ketty','Teacher');
insert into occs values ('Jane','Doctor');
insert into occs values ('Zhan','Doctor');

1 个答案:

答案 0 :(得分:2)

这是一个查询,可为您提供所需的结果。它使用CTE创建一个名称和职业及其职业内行号的表。然后,它使用条件聚合来构建输出表,将CTE结果分组到行号上:

WITH cte AS (
SELECT name, occupation, ROW_NUMBER() OVER (PARTITION BY occupation) AS rownum
FROM occs)
SELECT
    MAX(CASE WHEN occupation = 'Actor' THEN name END) AS Actor,
    MAX(CASE WHEN occupation = 'Teacher' THEN name END) AS Teacher,
    MAX(CASE WHEN occupation = 'Doctor' THEN name END) AS Doctor
FROM cte
GROUP BY rownum

输出:

Actor   Teacher Doctor
julia   ketty   Jane
meera   null    Zhan

Demo on dbfiddle

为避免指定列名,您将需要使用存储过程并创建动态SQL查询。