ORACLE-запрос с процентами от общего по категориям и подкатегориям - PullRequest
1 голос
/ 14 июня 2019

Запрос:

SELECT Year, Month,Sector, Subsector, sum(employed), sum(unemployed)
FROM dbo.workforce
where Year= 2017 and Month = 12 and Sector = any('0700','0500','0600')
group by Year, Month,Sector, Subsector

поверх моей таблицы возвращается:

> Year,Month,Sector,Subsector,SUM(Employed),SUM(Unemployed)
> "2017","12","0700","0720","30089","2348"
> "2017","12","0600","0630","16778","781"
> "2017","12","0500","0000","7332","1198"
> "2017","12","0600","0620","3741","338"
> "2017","12","0700","0710","56308","4493"
> "2017","12","0600","0610","105492","21966"

Мне нужно добавить столбцы для итогов и процентов для секторов и подсекторов следующим образом:

Year,Month,Sector,TotalSector,PercentageFromAllSectors,SubSector,TotalForSubsector,PercentageForSubsector
"2017","12","0700","6845","3,65","0720","2351","34,35"
"2017","12","0700","6845","3,65","0710","4494","65,65"

Полагаю, мне нужны 2 переменные, которые будут содержать значения для общего итога и итога для каждого сектора, а затем рассчитывать процент для секторов и подсекторов, но я не знаю, как сформулировать это.

1 Ответ

1 голос
/ 14 июня 2019

вы можете использовать соединение

select  a.Year, a.Month, a.Sector, a.Subsector, a.sum_employed
    , (a.sum_employed/b.tot_employed)*100, a.sum_unemployed, (a.sum_unemployed/b.tot_unemployed)*100
from (
  SELECT Year, Month,Sector, Subsector, sum(employed) sum_employed, sum(unemployed) sum_unemployed
  FROM dbo.workforce
  where Year= 2017 and Month = 12 and Sector = any('0700','0500','0600')
  group by Year, Month,Sector, Subsector
  ) a
  inner join  (
  SELECT Year, Month,Sector,sum(employed) tot_employed, sum(unemployed) tot_unemployed
  FROM dbo.workforce
  where Year= 2017 and Month = 12 and Sector = any('0700','0500','0600')
  group by Year, Month,Sector
)  b  on a.Year = b.Year 
        and a.Month = b.Month 
          and a.Sector = b.Sector 
...