计算每月销售额差异

时间:2018-04-24 14:51:29

标签: sql sql-server sql-server-2008

我正在尝试计算过去3年内销售额的月比差异。我有点坚持如何让历史月份的实际加入到历史月份+ 1个月的实际值。当月份是12月时,它不会显示在结果集中,导致1月的下个月不显示。

with _t1 as (
SELECT
Year(Invoicedate) as [Year]
,Month(Invoicedate) as [Month]
,Sum([TaxableSalesAmt]+[NonTaxableSalesAmt]+[FreightAmt]+[SalesTaxAmt]) as Revenue
FROM [InvoiceHistory]
where year(invoicedate) >= '2015'
group by Year(Invoicedate) ,Month(Invoicedate)
)
,_t2 as (
SELECT 
Year(Invoicedate) as [Year]
,Month(Invoicedate) as [Month]
,Sum([TaxableSalesAmt]+[NonTaxableSalesAmt]+[FreightAmt]+[SalesTaxAmt]) as Revenue
FROM [MAS_RDP].[dbo].[AR_InvoiceHistoryHeader]
where year(invoicedate) >= '2015'
group by Year(Invoicedate) ,Month(Invoicedate)
)

Select _t1.year
,_t1.Month
,_t1.Revenue
,_t2.year
,_t2.month
,_t2.Revenue
,_t2.Revenue-_t1.Revenue as GrowthActual
,(_t2.Revenue-_t1.Revenue)/_t2.Revenue*100 as GrowthPercent
from _t1
inner join _t2 on _t1.year = _t2.year and _t1.month = _t2.month-1
order by _t1.year, _t1.month

1 个答案:

答案 0 :(得分:2)

这主要取决于您不使用日期值作为日期。

您需要的日期逻辑是查找任意日期与invoicedate之间的月份差异,然后将该差异以月份的形式添加到相同的任意日期以获取该月的第一天。然后,您可以在此差异中添加或减去以查找之前或之后的数月。

你可以通过以下方式看到这个:

select getdate() as RightNow
      ,dateadd(day,  datediff(day  , 0, getdate())  , 0) as DayStart
      ,dateadd(month,datediff(month, 0, getdate())-1, 0) as PreviousMonthStart
      ,dateadd(month,datediff(month, 0, getdate())  , 0) as MonthStart
      ,dateadd(month,datediff(month, 0, getdate())+1, 0) as NextMonthStart

以下内容不仅适用于您,而且由于where条款中缺少功能而在较短的时间内运行:

with _t1 as
(
    select dateadd(month,datediff(month,0,Invoicedate),0) as InvoiceMonth
        ,sum([TaxableSalesAmt]
            +[NonTaxableSalesAmt]
            +[FreightAmt]
            +[SalesTaxAmt]
            ) as Revenue
    from [InvoiceHistory]
    where invoicedate >= '20150101'
    group by dateadd(month,datediff(month,0,Invoicedate),0)
)
,_t2 as
(
    select dateadd(month,datediff(month,0,Invoicedate),0) as InvoiceMonth
        ,dateadd(month,datediff(month,0,Invoicedate)-1,0) as PreviousInvoiceMonth
        ,sum([TaxableSalesAmt]
            +[NonTaxableSalesAmt]
            +[FreightAmt]
            +[SalesTaxAmt]
            ) as Revenue
    from [MAS_RDP].[dbo].[AR_InvoiceHistoryHeader]
    where invoicedate >= '20150101'
    group by dateadd(month,datediff(month,0,Invoicedate),0)
            ,dateadd(month,datediff(month,0,Invoicedate)-1,0)
)
select _t1.InvoiceMonth
    ,_t1.Revenue
    ,_t2.PreviousInvoiceMonth
    ,_t2.Revenue
    ,_t2.Revenue-_t1.Revenue as GrowthActual
    ,(_t2.Revenue - _t1.Revenue)/_t2.Revenue*100 as GrowthPercent
from _t1
    inner join _t2
        on _t1.InvoiceMonth = _t2.PreviousInvoiceMonth
order by _t1.InvoiceMonth