如何计算两列之间的差异与结果

时间:2016-03-04 16:34:36

标签: mysql sql

我可以计算每行的利润吗?

SELECT
SUM(CASE WHEN m.billable = 0 THEN r.rate ELSE 0 END) AS Revenue, -- 33 + 34 + 456 + 52...etc = 5500 
    SUM(CASE WHEN m.billable = 1 AND m.optimized = 0 THEN r.rate ELSE 0 END) AS Costs,-- 33 + 4...etc = 339 
    5500 - 339 AS Profit -- I need to get this difference 
    FROM messages AS m
JOIN rates AS r ON (r.id = m.rate_id    )
    GROUP BY
            m.client_account_id,
            m.mcc,
            m.mnc

enter image description here

enter image description here

我想要



| Revenue | Costs | Profit
   5500      500     5000




2 个答案:

答案 0 :(得分:2)

只需将其放在子查询中:

SELECT Revenue - Costs as Profit
FROM (
SELECT
SUM(CASE WHEN m.billable = 0 THEN r.rate ELSE 0 END) AS Revenue,  
SUM(CASE WHEN m.billable = 1 AND m.optimized = 0 THEN r.rate ELSE 0 END) AS Costs
) as temp

答案 1 :(得分:2)

将查询移动到子查询中,然后减去结果。

SELECT Revenue, Costs, Revenue - Costs AS Profit
FROM (
    SELECT
        SUM(CASE WHEN m.billable = 0 THEN r.rate ELSE 0 END) AS Revenue,
        SUM(CASE WHEN m.billable = 1 AND m.optimized = 0 THEN r.rate ELSE 0 END) AS Costs
    FROM YourTable) AS x

加入两个表,并显示按帐户分组的结果,它将是:

SELECT client_account_id, mmc, mnc, Revenue, Costs, Revenue - Costs AS Profit
FROM (
    SELECT
        m.client_account_id, m.mmc, m.mnc
        SUM(CASE WHEN m.billable = 0 THEN r.rate ELSE 0 END) AS Revenue,
        SUM(CASE WHEN m.billable = 1 AND m.optimized = 0 THEN r.rate ELSE 0 END) AS Costs
    FROM messages AS m
    JOIN rates AS r ON r.id = m.rate_id
    GROUP BY m.client_account_id, m.mmc, m.mnc
) AS x