如何重用两个计算列

时间:2017-10-11 15:06:38

标签: sql postgresql

   SELECT 

        day,
        SUM(profit) AS TotalProfit,
        SUM(revenue) AS TotalRevenue,
        TotalProfit/TotalRevenue AS ProfitMargin

    FROM table

它表示 TotalProfit 未列为表格 列。我想避免做SUM(利润)/ SUM(收入),因为真正的公式要复杂得多。

6 个答案:

答案 0 :(得分:2)

您无法在选择条款中引用别名。使用像sum

这样的聚合函数时,必须使用group by

选择

    day,
    SUM(profit) AS TotalProfit,
    SUM(revenue) AS TotalRevenue,
    SUM(profit)/SUM(revenue) AS ProfitMargin

FROM table

按天分组

答案 1 :(得分:1)

再次这样做:

 SELECT 
        day,
        SUM(profit) AS TotalProfit,
        SUM(revenue) AS TotalRevenue,
        SUM(profit)/SUM(revenue) AS ProfitMargin

    FROM table
    GROUP BY Day

答案 2 :(得分:1)

为了使用先前声明的别名使用子查询

SELECT day,TotalProfit, TotalRevenue, TotalProfit/TotalRevenue AS ProfitMargin
from (
SELECT 

        day,
        SUM(profit) AS TotalProfit,
        SUM(revenue) AS TotalRevenue
    FROM table
GROUP BY day
) as subq

当然我同意其他人看起来很开销

答案 3 :(得分:1)

SELECT *,TotalProfit/TotalRevenue AS ProfitMargin from
 (select
    day,
    SUM(profit) AS TotalProfit,
    SUM(revenue) AS TotalRevenue       
FROM table) x
where  

答案 4 :(得分:1)

您需要使用子查询。 然后,您可以使用data.TotalProfit / data.TotalRevenue AS ProfitMargin

SELECT 
   data.day
 , data.TotalProfit
 , data.TotalRevenue
 , (data.TotalProfit / data.TotalRevenue) AS ProfitMargin
FROM (
  SELECT
      day    
    , SUM(profit) AS TotalProfit
    , SUM(revenue) AS TotalRevenue
  FROM 
   table
)
 data

答案 5 :(得分:0)

我最喜欢的方法是横向连接。这看起来像:

SELECT . . . ,
       v.exp1, v.exp2, v.exp1 / v.exp2
FROM table t, LATERAL
     (VALUES (<expression1>, <expression2>) ) v(exp1, exp2);

但是,要将此与聚合查询一起使用,无论如何都需要子查询。如果您使用子查询,只需将计算放在外部查询中。