2017-03-02 57 views
0

我想在計算中使用別名,但我知道這不是正確的方法。好了,所以我的原代碼是這樣的如何在沒有多行的計算中使用別名

SELECT ROUND(SUM((`Unit_Cost`*`Quantity`)*`ExchangeRate`),2) as Cost, 
ROUND(SUM(`Unit_Cost`*`Quantity`)*`ExchangeRate`/`salesinvoice_products`.`VAT`,2) as `VATValue` 
FROM `salesinvoice` 
LEFT JOIN `customers` 
    ON `salesinvoice`.`customer_id` = `customers`.`customer_id` 
LEFT JOIN `salesinvoice_products` 
    ON `salesinvoice`.`SalesInvoice_id` = `salesinvoice_products`.`SalesInvoice_id` 
WHERE `PaymentTerms` > 1 
GROUP BY `salesinvoice`.`SalesInvoice_id` 
ORDER BY `DateEntered` DESC 

但我想給VATValue增加成本。很明顯,如果我只是做+ VATValue它會抱怨VATValue不存在,但這是它讀取別名的方式。所以接下來我試着用一個子查詢來思考這個答案。 因此,這裏是我的代碼使用子查詢

SELECT ROUND(SUM((`Unit_Cost`*`Quantity`)*`ExchangeRate`),2) as Cost, 
    (
    SELECT ROUND(SUM(`Unit_Cost`*`Quantity`)*`ExchangeRate`/`salesinvoice_products`.`VAT`,2) 
    FROM `salesinvoice` 
) as tVAT 
FROM `salesinvoice` 
LEFT JOIN `customers` 
    ON `salesinvoice`.`customer_id` = `customers`.`customer_id` 
LEFT JOIN `salesinvoice_products` 
    ON `salesinvoice`.`SalesInvoice_id` = `salesinvoice_products`.`SalesInvoice_id` 
WHERE `PaymentTerms` > 1 
GROUP BY `salesinvoice`.`SalesInvoice_id` 
ORDER BY `DateEntered` DESC 

不幸的是這一次它給出了一個錯誤#1242 - 子查詢返回多個1行。我知道我並沒有首先添加別名,但首先我只是確保子選擇的作用,而且顯然不是。

我相信我可能需要子查詢中的where子句,但我不確定。

誰能告訴我我做錯了什麼?

回答

1

而不是子查詢我會做以下幾點:

SELECT `Cost`, `VATValue`, (`VATValue`+`Cost`) as CostAndVAT 
FROM 
(SELECT ROUND(SUM((`Unit_Cost`*`Quantity`)*`ExchangeRate`),2) as Cost, 
ROUND(SUM(`Unit_Cost`*`Quantity`)*`ExchangeRate`/`salesinvoice_products`.`VAT`,2) as `VATValue` 
FROM `salesinvoice` 
LEFT JOIN `customers` 
ON `salesinvoice`.`customer_id` = `customers`.`customer_id` 
LEFT JOIN `salesinvoice_products` 
ON `salesinvoice`.`SalesInvoice_id` = `salesinvoice_products`.`SalesInvoice_id` 
WHERE `PaymentTerms` > 1 
GROUP BY `salesinvoice`.`SalesInvoice_id` 
ORDER BY `DateEntered` DESC) a