--■■■インラインビューを使わない方法■■■
select coalesce(CD,RPad(substr(CD,1,2),6,'0'),RPad(substr(CD,1,4),6,'0')) as CD,
sum(kingaku) as kingaku
from kingakuTable
group by grouping sets(CD,RPad(substr(CD,1,2),6,'0'),RPad(substr(CD,1,4),6,'0'))
order by CD;
--■■■インラインビューを使う方法■■■
select coalesce(CD,gp2,gp4) as CD,
sum(kingaku) as kingaku
from (select RPad(substr(CD,1,2),6,'0') as gp2,
RPad(substr(CD,1,4),6,'0') as gp4,
CD,kingaku
from kingakuTable)
group by grouping sets(CD,gp2,gp4)
order by CD;
--■■■grouping関数を使う方法■■■
select
case when grouping(CD) = 0 then CD
when grouping(RPad(substr(CD,1,2),6,'0')) = 0 then RPad(substr(CD,1,2),6,'0')
when grouping(RPad(substr(CD,1,4),6,'0')) = 0 then RPad(substr(CD,1,4),6,'0')
end as CD,
sum(kingaku) as kingaku
from kingakuTable
group by grouping sets(CD,RPad(substr(CD,1,2),6,'0'),RPad(substr(CD,1,4),6,'0'))
order by CD;