Как использовать результат псевдонимного имени в подзапросе в sql?

#sql #oracle

#sql #Oracle

Вопрос:

Пожалуйста, найдите запрос ниже. Например:

 Select (select count(loc_id) from TotalLocation_table) as TotalLocations,
 (select count(*) from EngagedccLocTable where loc in ( select loc_id from location_table) as EngageddLocations

//calculate the percentage of locations by using EngagedLocations and TotalLocations.used above queries to calculate percentage.

(select count(*) from EngagedccLocTable where loc in ( select loc_id from location_table)/(select count(loc_id) from TotalLocation_table)*100 as percentage

from loc_table;
  

Вместо того, чтобы использовать тот же запрос, я хочу использовать псевдонимы для вычисления процента.

Нравится (EngageddLocations/TotalLocations)*100 as percentage .

Как это использовать, пожалуйста, дайте мне знать.

Ответ №1:

Вы можете попробовать, как показано ниже

 Select (EngageddLocations / TotalLocations) * 100 as percentage
from
(
select count(tl.loc_id) as TotalLocations,
count(ec.loc) as EngageddLocations
from TotalLocation_table tl
JOIN EngagedccLocTable ec ON tl.loc_id = ec.loc
) X
  

Ответ №2:

 with EngageddLocations as (select count(*) as  Engagedd 
                           from EngagedccLocTable 
                           where loc in ( select loc_id 
                                          from location_table))
,   TotalLocations as (select count(loc_id) as total 
                       from TotalLocation_table)
select EngageddLocations.Engagedd as EngageddLocations
,      TotalLocations.Total as TotalLocations
,      (EngageddLocations.Engagedd, TotalLocations.Total*100) as percentage
from EngageddLocations
,    TotalLocations;