从emp表中显示工作,每个工作下的员工总数

时间:2013-09-03 18:42:54

标签: sql oracle11gr2

我希望输出如下:

----------

 job          count          ename
----------
salesman      4            name1
                           name2
                           name3
                           name4

clerk         4            name1
                           name2
                           name3
                           name4
manager       3            name1
                           name2
                           name3
analyst       2            name1
                           name2
president     1            name

......等等。

不应重复该职位的职位和计数。我有一个重复的答案。

1 个答案:

答案 0 :(得分:0)

SQL Fiddle

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"

<强> Results

|       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 |