0

これはよくある質問だと思いますが、私が説明している方法では解決策を見つけることができません。私のクエリは次のようなものです:

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

列が何であるかなどは実際には問題ではありません。この場合、重要な点は次のとおりです。Margin列は、計算するためにTotal CostsクエリとTotal Revenueクエリを繰り返す必要がありますが、これはばかげた方法のように思えます。しかし、どうやら私はただ言うことはできません"Total Revenue" - "Total Costs" AS "Margin

4

2 に答える 2

1

内部クエリを使用するだけで、コードを繰り返さずに同じことを実現できます。

SELECT TotalCosts, TotalRevenue, TotalCost - TotalRevenue AS Margin
FROM 
(
    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 TotalCosts,

    (
        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 TotalRevenue
) t

編集:この回答は、質問の最初のバージョンである集計関数を使用したものに基づいています。

于 2013-10-29T14:34:03.333 に答える