トップページに戻る    次のSQLパズルへ    前のSQLパズルへ

7-33 キーブレイク時に、指定行を出力その2

SQLパズル

empテーブル
dname       empno
----------  -----
accounting  9999
accounting  1111
research    5555
research    4444
research    3333
sales       8888
sales       7777
sales       6666

empテーブルを以下のように出力する。

order by dname,empno descでソートし、
dnameが変更されたら、**の行を出力する
ただし、最終行には**の行を出力しない。

出力結果
dname       empno
----------  -----
accounting  9999
accounting  1111
**          **
research    5555
research    4444
research    3333
**          **
sales       8888
sales       7777
sales       6666


データ作成スクリプト

前のSQLパズルと同じ


SQL

--■■■union allを使う方法■■■
select dname,empno
from (select nvl2(empno,dname,'**') as dname,
      nvl(empno,'**') as empno,
      Row_Number() over(order by dname,empno desc nulls Last) as Rank,
      count(*) over() as RecordCount
      from (select dname,empno from emp
            union all select distinct dname,null from emp))
where Rank != RecordCount
order by Rank;

--■■■rollupを使う方法1■■■
select dname,empno
from (select case grouping(empno) when 1 then '**' else dname end as dname,
             case grouping(empno) when 1 then '**' else empno end as empno,
      Row_Number() over(order by dname,grouping(empno),empno desc) as sortKey,
      count(*) over() as maxSortKey
        from emp
      group by rollup(dname,empno)
      having grouping_ID(dname,empno) != 3)
 where sortKey != maxSortKey
order by sortKey;

--■■■rollupを使う方法2■■■
select dname,empno
from (select case grouping(empno) when 1 then '**' else dname end as dname,
             case grouping(empno) when 1 then '**' else empno end as empno,
      Row_Number() over(order by dname,grouping(empno),empno desc) as sortKey,
      count(*) over() as maxSortKey
        from emp
      group by dname,rollup(empno))
 where sortKey != maxSortKey
order by sortKey;

--■■■grouping setsを使う方法■■■
select dname,empno
from (select case grouping(empno) when 1 then '**' else dname end as dname,
             case grouping(empno) when 1 then '**' else empno end as empno,
      Row_Number() over(order by dname,grouping(empno),empno desc) as sortKey,
      count(*) over() as maxSortKey
        from emp
      group by grouping sets((dname,empno),dname))
 where sortKey != maxSortKey
order by sortKey;


解説

count関数と、Row_Number関数を組み合わせてます。

Printing a blank line??