我想在计算中使用别名,但我知道这不是正确的方法。好的,我的原始代码就是这个
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子句,但我不确定。
谁能告诉我我做错了什么?
答案 0 :(得分: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