2016-03-04 69 views
0

我可以計算每行列利潤?如何計算兩列之間的差異與結果

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

將您的查詢移入子查詢,然後減去結果。

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 
+0

SELECT收入,COS ......從消息)爲X FROM爲M的郵件| 19:47:44內核錯誤:錯誤(1064)42000:「您的SQL語法有錯誤;請檢查與您的MySQL服務器版本對應的手冊,以便在'FROM消息附近使用AS m FROM消息AS m – AxOn

+0

在同一查詢中不能有兩個FROM字段 – Barmar

+0

我更新了更全面的查詢,但我需要使用消息表/我們可以用它做什麼? – AxOn

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 
相關問題