如何使用百分比插入新行

时间:2014-10-16 10:34:31

标签: sql oracle

我有这个问题:

select t.cod_provincia as prov, COUNT(t.cod_provincia) as conto
from clienti t 
where t.data_ins between to_date(&da_data,'ddmmrr') and to_date(&a_data,'ddmmrr')
and t.cod_iso='ITA'
group by t.cod_provincia

它返回

enter image description here

现在我想要一个新的col来查看每行的CONTO值百分比。我能做到吗? 对于每一行,我想要值[CONTO*100]/SUM(CONTO)

3 个答案:

答案 0 :(得分:1)

select pov, conto*100/sum(conto) over()
  from (
       select t.cod_provincia as prov, COUNT(t.cod_provincia) as conto
         from clienti t 
        where t.data_ins between to_date(&da_data,'ddmmrr') and to_date(&a_data,'ddmmrr')
          and t.cod_iso='ITA'
        group by t.cod_provincia
       )

答案 1 :(得分:0)

Oracle具有内置的分析函数RATIO_TO_REPORT,可用作Rusty解决方案的替代方案:

select t.cod_provincia as prov,
       count(t.cod_provincia) as conto,
       100*RATIO_TO_REPORT(count(t.cod_provincia)) OVER () as percentage 
from clienti t 
where t.data_ins between to_date(&da_data,'ddmmrr') and to_date(&a_data,'ddmmrr')
and t.cod_iso='ITA'
group by t.cod_provincia

它给出相同的结果,但避免重复表达式作为分子和分母中的和。而且您不必担心零错误可能导致的划分。

答案 2 :(得分:-1)

SELECT t.cod_provincia        AS prov,
       Count(t.cod_provincia) AS conto,
       ( Count(t.cod_provincia) * 100 ) / Sum(cod_provincia)
FROM   clienti t
WHERE  t.data_ins between to_date(&da_data,'ddmmrr') and to_date(&a_data,'ddmmrr')
and    t.cod_iso = 'ITA'
GROUP  BY t.cod_provincia