备注:测试数据库版本为MySQL 8.0
如需要scott用户下建表及录入数据语句,可参考:
scott建表及录入数据sql脚本
一.需求
生成一个从底部向上延伸的直方图。
例如,采用纵向直方图显示每个部门的职员数,一个星号"*"表示一个员工。
返回结果集应该如:
±-----±-----±-----+
| d10 | d20 | d30 |
±-----±-----±-----+
| * | * | * |
| * | * | * |
| * | * | * |
| NULL | * | * |
| NULL | * | * |
| NULL | NULL | * |
±-----±-----±-----+
二.解决方案
select max(deptno_10) as d10,
max(deptno_20) as d20,
max(deptno_30) as d30
from (
select case when e.deptno = 10 then '*' else null end deptno_10,
case when e.deptno = 20 then '*' else null end deptno_20,
case when e.deptno = 30 then '*' else null end deptno_30,
( select count(*) from emp d
where e.deptno = d.deptno and e.empno < d.empno ) as rnk
from emp e
) x
group by rnk
order by 1 desc, 2 desc, 3 desc;
测试记录:
mysql> select max(deptno_10) as d10,
-> max(deptno_20) as d20,
-> max(deptno_30) as d30
-> from (
-> select case when e.deptno = 10 then '*' else null end deptno_10,
-> case when e.deptno = 20 then '*' else null end deptno_20,
-> case when e.deptno = 30 then '*' else null end deptno_30,
-> ( select count(*) from emp d
-> where e.deptno = d.deptno and e.empno < d.empno ) as rnk
-> from emp e
-> ) x
-> group by rnk
-> order by 1 desc, 2 desc, 3 desc;
+------+------+------+
| d10 | d20 | d30 |
+------+------+------+
| * | * | * |
| * | * | * |
| * | * | * |
| NULL | * | * |
| NULL | * | * |
| NULL | NULL | * |
+------+------+------+
6 rows in set (0.00 sec)
「喜欢这篇文章,您的关注和赞赏是给作者最好的鼓励」
关注作者
【版权声明】本文为墨天轮用户原创内容,转载时必须标注文章的来源(墨天轮),文章链接,文章作者等基本信息,否则作者和墨天轮有权追究责任。如果您发现墨天轮中有涉嫌抄袭或者侵权的内容,欢迎发送邮件至:contact@modb.pro进行举报,并提供相关证据,一经查实,墨天轮将立刻删除相关内容。




