我確定這是一個常見問題,但我無法以我描述的方式找到解決方案。我的查詢是這樣的:MySQL:使用兩列的值來計算第三個
SELECT
(
SELECT SUM(finance_transaction_components.invoiced_price)
FROM finance_transactions
JOIN finance_transaction_components ON finance_transaction_components.transaction_id = finance_transactions.id
JOIN agents ON agents.id = finance_transactions.agent_id
WHERE DATE_FORMAT(finance_transactions.completed_date, "%Y-%m-%d") BETWEEN "2013-10-01" AND "2013-10-29"
) AS "Total Costs",
(
SELECT SUM(finance_transactions.agent_price)
FROM finance_transactions
JOIN agents ON agents.id = finance_transactions.agent_id
WHERE finance_transactions.product_id != 10
AND DATE_FORMAT(completed_date, "%Y-%m-%d") BETWEEN "2013-10-01" AND "2013-10-29"
) AS "Total Revenue",
(
SELECT SUM(finance_transactions.agent_price)
FROM finance_transactions
JOIN agents ON agents.id = finance_transactions.agent_id
WHERE finance_transactions.product_id != 10
AND DATE_FORMAT(completed_date, "%Y-%m-%d") BETWEEN "2013-10-01" AND "2013-10-29"
AND IF(finance_transactions.lldrg > 0, IF(finance_transactions.lldrg = 1, 0, 1) ,1) = 1
) - (SELECT SUM(finance_transaction_components.invoiced_price)
FROM finance_transactions
JOIN finance_transaction_components ON finance_transaction_components.transaction_id = finance_transactions.id
JOIN agents ON agents.id = finance_transactions.agent_id
WHERE DATE_FORMAT(finance_transactions.completed_date, "%Y-%m-%d") BETWEEN "2013-10-01" AND "2013-10-29"
) AS "Margin"
FROM finance_transactions
GROUP BY finance_transactions.agent_id
這並不重要,什麼列等等。在這種情況下,最重要的一點是這樣的:的保證金列需要重複總成本和總收入查詢計算,這似乎是一個愚蠢的做法。但顯然我不能只說"Total Revenue" - "Total Costs" AS "Margin
。
我看到您剛剛刪除了聚合函數。如果每個子查詢返回多於一行的話,您將如何鏈接收入和成本? –
對不起,我現在已經回滾了編輯。我想我可以通過編輯簡化其他讀者的問題。 – Jack