SQL - 来自YTD的MTD编号,缺少数字

时间:2017-10-04 01:37:03

标签: sql sql-server tsql

以下是我的查询。 简而言之,我的数据是年初至今的数字,因此查询通过获取当前月份减去月份1来计算月初至今的变动。

如果当前月份包含前一个月的所有组合,则效果很好。但本月其中一个组合已经为零 - 因此YTD = 0并且9月没有记录。

但是记录仍然存在于8月,所以它应该给我一个动作,即8月显示100和9月什么也没有显示。所以运动应该是0-100 = -100。

我不知道如何调整查询,我必须首先说明我需要哪个月,其中curr.month = 9,但由于9月份组合不存在,我的连接效果不好。请帮忙。它使用Sep数据作为基础,它应该使用Aug和Sep组合。

 SELECT curr.[Month], 
     curr.[GRCARef], 
     curr.[IEItem],
     curr.currYTD, 
     prev.prevYTD, 
   CASE curr.[Month]
   When 1 then currYTD
   ELSE
   cast((currYTD - COALESCE(prevYTD,0)) as numeric(15,2))
   END as MTD

FROM   

   (SELECT [Month], 
           [GRCARef],
           [Ac Code] IEItem,
           sum([BalLCY]) currYTD
   FROM    [PWC_2017Q2].[dbo].[SS620_PL_FullYear]
   Group by  [Month], [Bch], [GRCARef],[Ac Code], [ProdType],[GHO]
   )  curr

   Full Outer JOIN 

   (SELECT [Month], 
           [GRCARef],
           [Ac Code] IEItem, 
           sum([BalLCY]) prevYTD
    FROM   [PWC_2017Q2].[dbo].[SS620_PL_FullYear]
    Group by  [Month], [Bch], [GRCARef], [Ac Code], [ProdType],[GHO]
    )   prev

    ON  curr.[GRCARef] = prev.[GRCARef]
    and curr.[IEItem] = prev.[IEItem]
    and curr.[Month] - 1 = prev.[Month] 
       -- Join with Month -1

where 
curr.[MONTH] = 9

2 个答案:

答案 0 :(得分:0)

试试这个。

cast((ISNULL(currYTD,0) - COALESCE(prevYTD,0)) as numeric(15,2))

答案 1 :(得分:0)

您需要强制存在几个月,然后加入您的摘要:

;with
m as (
    -- get numbers from 1 to 12
    select top 12 ROW_NUMBER() over (order by id) [Month]
    from sysobjects
),
g as (
   SELECT [Month], [GRCARef], [Ac Code] IEItem, sum([BalLCY]) YTD
   FROM [PWC_2017Q2].[dbo].[SS620_PL_FullYear]
   Group by [Month], [Bch], [GRCARef], [Ac Code], [ProdType], [GHO]
)
select 
    m.[Month], 
    ISNULL(curr.GRCARef, prev.GRCARef) GRCARef, 
    ISNULL(curr.IEItem, prev.IEItem) IEItem, 
    ISNULL(curr.YTD, 0) currYTD, ISNULL(prev.YTD, 0) prevYTD, 
    ISNULL(curr.YTD, 0) - ISNULL(prev.YTD, 0) MTD
from m
left join g curr on m.[Month] = curr.[Month]
left join g prev on m.[Month] = prev.[Month] + 1
where 
    m.[Month] = 9

请注意,你的小组中[Bch], [ProdType], [GHO]不应该在那里..如果它们是“不相关的”只是删除它们,如果它们是相关的,你应该把它们放在select子句中,也在连接条件中

修改 如果您使用SQL Server 2012及更高版本,您还可以使用LAG函数来获取上个月的摘要:

;with
m as (
    -- get numbers from 1 to 12
    select top 12 ROW_NUMBER() over (order by id) [Month]
    from sysobjects
),
g as (
   SELECT [Month], [GRCARef], [Ac Code] IEItem, sum([BalLCY]) YTD
   FROM [PWC_2017Q2].[dbo].[SS620_PL_FullYear]
   Group by [Month], [Bch], [GRCARef], [Ac Code], [ProdType], [GHO]
)
f as (
select 
    m.[Month], GRCARef, IEItem, ISNULL(YTD, 0) currYTD, ISNULL(LAG(YTD, 1, 0) over (order by m.[Month]), 0) as prevYTD
from m
left join g curr on m.[Month] = curr.[Month]
)
select *, currYTD-prevYTD MTD
from f
where 
    [Month] = 9
order by [Month]