我想在我的sql项目中同时使用子查询和计算 我有一张表A,其中包含以下信息:
表A
if (isset($_POST["X"])) {
$x = $_POST["X"];
echo $x;
}else{
echo 'no variable received';
}
我想找到1月,2月的贡献边际以及1月和2月之间的边际差异。我可以在一个查询中做到这一点以及如何做到这一点?
显示器应具有以下格式:
Month_revenue Income Cost
-------------------------
Jan 100 50
Feb 90 60
Mar 80 40
谢谢!
答案 0 :(得分: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;