2016-05-13 123 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;