-2

次のような出力が必要です。

----------

 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

.......等々。

役職名とその役職の名前ごとに数を繰り返すべきではありません。繰り返しで答えが出ました。

4

1 に答える 1

0

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 |
于 2013-09-03T19:30:21.677 に答える