SQL小提琴
Oracle 11g R2 模式设置:
CREATE TABLE employee
("job" varchar2(9), "ename" varchar2(5))
;
INSERT ALL
INTO employee ("job", "ename")
VALUES ('salesman', 'name1')
INTO employee ("job", "ename")
VALUES ('salesman', 'name4')
INTO employee ("job", "ename")
VALUES ('clerk', 'name1')
INTO employee ("job", "ename")
VALUES ('clerk', 'name2')
INTO employee ("job", "ename")
VALUES ('manager', 'name1')
INTO employee ("job", "ename")
VALUES ('manager', 'name2')
INTO employee ("job", "ename")
VALUES ('manager', 'name3')
INTO employee ("job", "ename")
VALUES ('salesman', 'name2')
INTO employee ("job", "ename")
VALUES ('salesman', 'name3')
INTO employee ("job", "ename")
VALUES ('clerk', 'name3')
INTO employee ("job", "ename")
VALUES ('president', 'name')
INTO employee ("job", "ename")
VALUES ('clerk', 'name4')
INTO employee ("job", "ename")
VALUES ('analyst', 'name1')
INTO employee ("job", "ename")
VALUES ('analyst', 'name2')
SELECT * FROM dual
;
查询 1:
SELECT case when j."ename" = firstname then j."job" else ' ' end as job,
case when j."ename" = firstname then cast(c.cnt as varchar(5)) else ' ' end as "count",
j."ename"
FROM employee j
INNER JOIN (SELECT "job", min("ename") as firstname, count(*) as cnt FROM employee GROUP BY "job") c ON c."job" = j."job"
ORDER BY cnt desc, j."job", j."ename"
结果:
| JOB | COUNT | ENAME |
|-----------|-------|-------|
| clerk | 4 | name1 |
| | | name2 |
| | | name3 |
| | | name4 |
| salesman | 4 | name1 |
| | | name2 |
| | | name3 |
| | | name4 |
| manager | 3 | name1 |
| | | name2 |
| | | name3 |
| analyst | 2 | name1 |
| | | name2 |
| president | 1 | name |