将结果与两个条件的子查询相除

时间:2019-06-15 03:36:46

标签: sql postgresql

我想将同一表中两个子查询的结果除以不同 Postgres中的where条件

select (a / b) as result from 
    (select sum(price) as sales from transactions where order_type = 'return') as a,
    (select sum(price) as sales from transactions where order_type = 'sale') as b

2 个答案:

答案 0 :(得分:0)

我认为您不需要在其中使用别名,您可以选择部门本身,例如,尝试以下操作:

select (select sum(price) from transactions where order_type = 'return') / (select sum(price) from transactions where order_type = 'sale') as result;

在假设的transactions表中,如下所示:

 price | order_type
-------+------------
     4 | return
     5 | sale
     6 | return
(3 rows)

该查询将输出以下内容:

 result
--------
      2
(1 row)

因为(4 + 6)/ 5 = 2

HIH

答案 1 :(得分:0)

您的代码应该没问题。您可以更通俗地写为:

select ( sum(price) filter (where order_type = 'return') /
         sum(price) filter (where order_type = 'sale')
       ) as result
from transactions;

这只会扫描transactions表一次。

如果没有销售,这样做的确有除零错误的风险。如果可能的话:

select ( sum(price) filter (where order_type = 'return') /
         nullif(sum(price) filter (where order_type = 'sale'), 0)
       ) as result
from transactions;