在SQL中划分两个自定义表

时间:2018-02-03 14:16:51

标签: sql

我有一个很长的SQL查询。此查询返回两列pop2068ratio。查询如下:

with CTE as
(
    select 
        name,  
        (select 
             sum(c.population * (select power(p.population_growth/100+1,50))) 
                                 from country c 
                                 join population p on c.code = p.country 
                                 where code in (select country
                                                from encompasses 
                                                where continent = continent.name)) as pop2068, 
       (select sum(population) 
        from country 
        where code in (select country 
                       from encompasses 
                       where continent = continent.name)) as ratio 
    from 
        continent
) 
select * 
from CTE

运行此查询会返回以下结果:

       name        |              pop2068               |   ratio
-------------------+------------------------------------+------------
 Asia              |    7688004586.16569723635392885320 | 4415908810
 Australia/Oceania | 474230639.524099258085328372951611 |  289808388

但我希望ratio列代替pop2068/ratio

关于如何解决这个问题的任何想法?

祝福!

2 个答案:

答案 0 :(得分:1)

Mabye你可以在最后一次查询中使用它。

我的意思是你可以用它。

with CTE (name,pop2068,ratio) as
(
    select name
    ,  
    (
        select sum(c.population * (select power(p.population_growth/100+1,50))) 
        from country c 
        join population p 
            on c.code = p.country 
        where code in
        (
            select country
            from encompasses 
            where continent = continent.name
        )
    ) as pop2068
    , 
    (
        select sum(population) 
        from country 
        where code
        in
        (
            select country 
            from encompasses 
            where continent = continent.name
        )
    ) as ratio 
    from continent
) 
select name,pop2068,(pop2068/ratio) as ratio from CTE

答案 1 :(得分:0)

你可以给别名;

select pop2068/ratio as pop2068ratio from CTE