oracle—列sql百分比的总和

gpnt7bae  于 2021-07-29  发布在  Java
关注(0)|答案(1)|浏览(428)

我正在试图得到最终的记录作为总数和百分比:

SELECT  region,  count(*) as total, concat(to_char(round(count(*) * 100/ sum(count(*)) over() ,2),'990.99'),
'%') perc
FROM (SELECT 
    CASE
                 WHEN Substr(veh_vin, 1, 1) >= 'A' 
                      AND Substr(veh_vin, 1, 1) <= 'C' THEN 'America' 
                 WHEN Substr(veh_vin, 1, 1) >= 'J' 
                      AND Substr(veh_vin, 1, 1) <= 'R' THEN 'Poland' 
                 WHEN Substr(veh_vin, 1, 1) >= 'S' 
                      AND Substr(veh_vin, 1, 1) <= 'Z' THEN 'Euro' 
                 WHEN Substr(veh_vin, 1, 1) BETWEEN 1 AND 5 THEN 'North Africa' 
                 WHEN Substr(veh_vin, 1, 1) BETWEEN 6 AND 7 THEN 'Australia' 
                 WHEN Substr(veh_vin, 1, 1) BETWEEN 8 AND 9 THEN 'China' 
                 ELSE 'UNKNOWN' 
               END AS region 
        FROM   vehicle) s 
GROUP  BY region 
UNION 
SELECT 'Total' Region, 
       Count(*) TOTAL, 
       concat(to_char(count(*) * 100/ sum(count(*)) over(),'990.99'),
'%') perc       
FROM vehicle ;

我明白了:

Region        TOTAL   PERC
         America       66     31.28%
         Poland        89     42.18%
         Europe         1     .47%
       Australia       1      .47%
         China        54      25.59%
          Total          211    100.00%

期望值为:

Region        TOTAL   PERC
     America       66     31.28%
     Poland        89     42.18%
     Europe         1     0.47%
   Australia       1      0.47%
     China        54      25.59%
   Total          211    99.99%

我试图得到99.99的值,即perc列的总和,我该怎么做?

kupeojn6

kupeojn61#

这符合要求

with regions as (
SELECT  region,  count(*) as total, round(count(*) * 100/ sum(count(*)) over(),2) perc
FROM (SELECT 
    CASE
                 WHEN Substr(veh_vin, 1, 1) >= 'A' 
                      AND Substr(veh_vin, 1, 1) <= 'C' THEN 'America' 
                 WHEN Substr(veh_vin, 1, 1) >= 'J' 
                      AND Substr(veh_vin, 1, 1) <= 'R' THEN 'Poland' 
                 WHEN Substr(veh_vin, 1, 1) >= 'S' 
                      AND Substr(veh_vin, 1, 1) <= 'Z' THEN 'Euro' 
                 WHEN Substr(veh_vin, 1, 1) BETWEEN 1 AND 5 THEN 'North Africa' 
                 WHEN Substr(veh_vin, 1, 1) BETWEEN 6 AND 7 THEN 'Australia' 
                 WHEN Substr(veh_vin, 1, 1) BETWEEN 8 AND 9 THEN 'China' 
                 ELSE 'UNKNOWN' 
               END AS region 
        FROM   vehicle) s 
GROUP  BY region )
select region, total, concat(to_char(perc,'990.99'), '%') perc from regions
union all
select 'Total' region, sum(Total) total, concat(to_char(sum(Perc),'990.99'), '%') perc
from regions

相关问题