如何使用PostgreSQL中之前定义的列进行计算?

时间:2014-09-30 16:23:54

标签: postgresql

我目前正在尝试使用之前声明的列来计算列。我认为这可以在MySQL中运行,但我不确定如何在PostgreSQL中做到这一点。

我的陈述如下:

SELECT customerNumber, customerName, (
    SELECT COALESCE(SUM(payments.amount), 0)
    FROM payments
    WHERE customers.customerNumber = payments.customerNumber
  ) as totalOfPaymentsMade,(
    SELECT COALESCE(SUM(orderdetails.priceeach * orderdetails.quantityordered), 0)
    FROM orders
    LEFT JOIN orderdetails ON orderdetails.ordernumber = orders.ordernumber
    WHERE customers.customerNumber = orders.customerNumber
  ) as totalValueOfAllOrdersMade, creditLimit, creditLimit + totalOfPaymentsMade - totalValueOfAllOrdersMade as amountOfAvailableCredit
FROM customers
ORDER BY customerNumber

我收到以下错误消息:column "totalofpaymentsmade" does not exist LINE 11: ...lValueOfAllOrdersMade, creditLimit, creditLimit + totalOfPay...

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT 
   *,
   creditLimit + totalOfPaymentsMade - totalValueOfAllOrdersMade 
   as amountOfAvailableCredit
from
(

SELECT 
    customerNumber, 
    customerName, 
    creditLimit,

    (
      SELECT COALESCE(SUM(payments.amount), 0)
      FROM payments
      WHERE customers.customerNumber = payments.customerNumber
    ) 
    as totalOfPaymentsMade,

    (
      SELECT COALESCE(SUM(orderdetails.priceeach * orderdetails.quantityordered), 0)
      FROM orders
      LEFT JOIN orderdetails ON orderdetails.ordernumber = orders.ordernumber
      WHERE customers.customerNumber = orders.customerNumber
    ) 
    as totalValueOfAllOrdersMade 

FROM customers

) a

ORDER BY customerNumber