社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  DATABASE

如何在mysql pivot中动态添加列并按空分组?

ravi • 5 年前 • 1343 次点击  

我有一张表,上面有姓名和职业的值。我试着做两件事

  1. 旋转工作台(已实现)
  2. 根据值动态添加/删除列
  3. 减少透视后列中的空值

我的疑问是:

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。 有没有一种方法可以扫描表并获取列,而不必手动执行DISTINCT。

问题的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');
Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/43586
 
1343 次点击  
文章 [ 1 ]  |  最新文章 5 年前