我正在使用Microsoft SQL Server 2008
我试图得到前3个月的平均利润,然后得到上个月的利润,然后我想执行一个计算,将上个月的利润与前3个月的平均利润进行比较。
所以举个例子:
本月利润之和-2本月利润之和-3本月利润之和-4
平均值(本月利润之和-2 +本月利润之和-3 +本月利润之和-4) =前3个月的平均值
前3个月平均数/上月利润总和=差额
到目前为止,我拥有的代码是:
select SUM(profit)as 'threemonthavg'
from invoices
where DATEPART(MM, SHIPPED_DATE) = DATEPART(MM, Dateadd(MM, -2, getdate()))
and DATEPART(YYYY, shipped_date) = DATEPART(YYYY, Dateadd(MM, -2, getdate()))
union
select SUM(profit)
from invoices
where DATEPART(MM, SHIPPED_DATE) = DATEPART(MM, Dateadd(MM, -3, getdate()))
and DATEPART(YYYY, shipped_date) = DATEPART(YYYY, Dateadd(MM, -3, getdate()))
union
select SUM(profit)
from invoices
where DATEPART(MM, SHIPPED_DATE) = DATEPART(MM, Dateadd(MM, -4, getdate()))
and DATEPART(YYYY, shipped_date) = DATEPART(YYYY, Dateadd(MM, -4, getdate()))这给出了3个单元格中每个月利润的总和。太完美了。现在我想对这些数字求平均值,因此我将其放在一个子查询中:
select AVG([threemonthavg])
from
(
select SUM(profit) as 'threemonthavg'
from invoices
where DATEPART(MM, SHIPPED_DATE) = DATEPART(MM, Dateadd(MM, -2, getdate()))
and DATEPART(YYYY, shipped_date) = DATEPART(YYYY, Dateadd(MM, -2, getdate()))
union
select SUM(profit)
from invoices
where DATEPART(MM, SHIPPED_DATE) = DATEPART(MM, Dateadd(MM, -3, getdate()))
and DATEPART(YYYY, shipped_date) = DATEPART(YYYY, Dateadd(MM, -3, getdate()))
union
select SUM(profit)
from invoices
where DATEPART(MM, SHIPPED_DATE) = DATEPART(MM, Dateadd(MM, -4, getdate()))
and DATEPART(YYYY, shipped_date) = DATEPART(YYYY, Dateadd(MM, -4, getdate()))
)x...so现在我有了我的平均值。现在我需要上个月的利润,这很容易获得,但是我如何将上面的查询与上个月的利润查询合并,以便执行除法计算?我尝试过许多连接,但是我不能得到正确的语法。有人能给我指个方向吗?
发布于 2014-04-08 06:31:00
为每个查询声明变量以存储到查询结果中,然后执行除法。这里有几个声明变量的例子.
声明@iVariable INT,@vVariable VARCHAR(100),@dDateTime DATETIME
设置@iVariable =1
SET @vVariable = 'myvar‘
SET @dDateTime = GETDATE()
选择@iVariable iVar、@vVariable vVar、@dDateTime dDT
去
https://stackoverflow.com/questions/22924134
复制相似问题