MySQL中的NPV计算

时间:2017-09-26 16:57:32

标签: php mysql finance

我有一个查询,根据购买数据的两个表提供我的成本结构的P& L视图。

Select Left(A.Location, 5) as Site, A.Account, A.Category, A.Sub_Category,
sum(If(Month(Inv.Invoice_Date)=1, A.Cost, 0)) as Jan,
sum(If(Month(Inv.Invoice_Date)=2, A.Cost, 0)) as Feb,
sum(If(Month(Inv.Invoice_Date)=3, A.Cost, 0)) as Mar,
sum(If(Month(Inv.Invoice_Date)=4, A.Cost, 0)) as Apr,
sum(If(Month(Inv.Invoice_Date)=5, A.Cost, 0)) as May,
sum(If(Month(Inv.Invoice_Date)=6, A.Cost, 0)) as Jun,
sum(If(Month(Inv.Invoice_Date)=7, A.Cost, 0)) as Jul,
sum(If(Month(Inv.Invoice_Date)=8, A.Cost, 0)) as Aug,
sum(If(Month(Inv.Invoice_Date)=9, A.Cost, 0)) as Sep,
sum(If(Month(Inv.Invoice_Date)=10, A.Cost, 0)) as Oct,
sum(If(Month(Inv.Invoice_Date)=11, A.Cost, 0)) as Nov,
sum(If(Month(Inv.Invoice_Date)=12, A.Cost, 0)) as Dece,
sum(Inv.Cost) as Total,
From Table.A as A
Left join (Select Invoice_Number, Invoice_Line_Number, Invoice_Date, group by Invoice_Number, Invoice_Line_Number) as Inv
on Inv.Invoice_Number = A.Invoice_Number and Inv.Invoice_Line_Number = A.Invoice_Line_Number
Where Left(A.Location_Desc, 5) = 'TEX01'
and Year(Inv.Invoice_Date) = '2016'
Group by Site, Account, Category, Sub_Category
Having Total <> 0
;

到目前为止一切顺利。现在我需要做三件我一直在努力的事情:

1)我需要在每个月底部的每行总成本行 - 这可能吗? 2)我需要在运行查询之前添加可以修改的变量行。例如,如果我找到一个降低X成本的投资机会,我希望能够引入一行从成本总计中减去该金额以显示节省。 3)我需要计算成本节约投资的净现值。这引发了另一个问题。该查询仅构建为带来1年的数据,但NPV计算需要5到10年的预测。

最优查询将平均网站的成本并将该未来成本与该平均值进行预测 - 然后它将引入通过新投资降低成本的变量行,并且最终将执行NPV计算以确定是否投资值得追求。

我的问题是:

a)MySQL是否是正确的工具? b)我知道从一个简单的select语句中这是不可能的 - view语句在这里不起作用,因为我在Select语句中有一个子查询。我应该构建一个新的表来保存查询的输出作为数据,并使用该表来执行所有这些? c)我应该查看编程语言/ MySQL解决方案吗?

谢谢!

1 个答案:

答案 0 :(得分:1)

对于第一点,您可以使用以下查询

获得结果
 Select Left(A.Location, 5) as Site, A.Account, A.Category, A.Sub_Category,
sum(If(Month(Inv.Invoice_Date)=1, A.Cost, 0)) as Jan,
sum(If(Month(Inv.Invoice_Date)=2, A.Cost, 0)) as Feb,
sum(If(Month(Inv.Invoice_Date)=3, A.Cost, 0)) as Mar,
sum(If(Month(Inv.Invoice_Date)=4, A.Cost, 0)) as Apr,
sum(If(Month(Inv.Invoice_Date)=5, A.Cost, 0)) as May,
sum(If(Month(Inv.Invoice_Date)=6, A.Cost, 0)) as Jun,
sum(If(Month(Inv.Invoice_Date)=7, A.Cost, 0)) as Jul,
sum(If(Month(Inv.Invoice_Date)=8, A.Cost, 0)) as Aug,
sum(If(Month(Inv.Invoice_Date)=9, A.Cost, 0)) as Sep,
sum(If(Month(Inv.Invoice_Date)=10, A.Cost, 0)) as Oct,
sum(If(Month(Inv.Invoice_Date)=11, A.Cost, 0)) as Nov,
sum(If(Month(Inv.Invoice_Date)=12, A.Cost, 0)) as Dece,
sum(Inv.Cost) as Total,
From Table.A as A
Left join (Select Invoice_Number, Invoice_Line_Number, Invoice_Date, group by Invoice_Number, Invoice_Line_Number) as Inv
on Inv.Invoice_Number = A.Invoice_Number and Inv.Invoice_Line_Number = A.Invoice_Line_Number
Where Left(A.Location_Desc, 5) = 'TEX01'
and Year(Inv.Invoice_Date) = '2016'
Group by A.Site, A.Account, A.Category, A.Sub_Category with ROLLUP Having Total <> 0 AND 
((a.Site is null or A.Account is not null) and (A.Account is null or A.Category is not null) and (A.Category is null or A.Sub_Category is not null));