2014-09-30 88 views
0

我正在嘗試使用先前聲明的列來計算列。我認爲這將在MySQL中起作用,但我不確定PostgreSQL中該如何做。如何使用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...

+0

不要你錯過了GROUP BY中的款項報表? – CapelliC 2014-09-30 16:27:23

+0

我想我現在不需要GROUP BY語句,因爲我使用的是subquerys,並且希望SUM匹配我的WHERE子句的所有行。 – Sebastian 2014-09-30 16:36:31

回答

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 
+0

非常感謝!爲我節省了幾個小時! – Sebastian 2014-09-30 23:29:09