2016-05-13 180 views
-2

我想在同一時間使用子查詢和計算我的SQL項目 我哪裏有下列信息的表答:計算邊際貢獻

表A

Month_revenue Income Cost 
------------------------- 
Jan   100 50 
Feb   90  60 
Mar   80  40 

我想找出1月份,2月份的利潤率和1月至2月份的利潤差異。我可以在一個查詢中這樣做嗎?

顯示屏應具有以下格式:

Jan  Feb  Mar   Jan/Feb   Feb/Mar 
--------------------------------------------------------------- 
100-50 90 - 60 80-40 (100-50) - (90-60) (90-60) - (80-40) 

謝謝!

+0

定義'貢獻Margin'?只是來自'收入 - 成本'的數字,或者你想要一個像'100 - 50'這樣的字符串? \t請閱讀[**如何提問**](http://stackoverflow.com/help/how-to-ask) \t \t這裏是[** START **]( http://spaghettidba.com/2015/04/24/how-to-post-at-sql-question-on-a-public-forum/)瞭解如何提高您的問題質量並獲得更好的答案。 –

+0

所以你想要一列五列,而不是五列結果?並且保證只有三個記錄,一個是一月,一個是二月,一個是三月在你的桌子上? –

+0

你正在尋找數據透視表...這是一個很好的例子http://stackoverflow.com/a/26297463/3470178 –

回答

0

您可以簡單地使用三個選項表:

select 
    jan.income - jan.cost as jan, 
    feb.income - feb.cost as feb, 
    mar.income - mar.cost as mar, 
    (jan.income - jan.cost) - (feb.income - feb.cost) as jan_feb, 
    (feb.income - feb.cost) - (mar.income - mar.cost) as feb_mar 
from 
    (select * from mytable where Month_revenue = 'Jan') jan 
cross join 
    (select * from mytable where Month_revenue = 'Feb') feb 
cross join 
    (select * from mytable where Month_revenue = 'Mar') mar; 

或者你也可以有條件地彙總:

select 
    sum(case when Month_revenue = 'Jan' then income - cost end) as jan, 
    sum(case when Month_revenue = 'Feb' then income - cost end) as feb, 
    sum(case when Month_revenue = 'Mar' then income - cost end) as mar, 
    sum(case when Month_revenue = 'Jan' then income - cost end) - 
    sum(case when Month_revenue = 'Feb' then income - cost end) as jan_feb, 
    sum(case when Month_revenue = 'Feb' then income - cost end) - 
    sum(case when Month_revenue = 'Mar' then income - cost end) as feb_mar 
from mytable;