在同一查询中计算年初至今的年初至今

时间:2019-03-20 15:46:35

标签: sql tsql sql-server-2008

如何在同一查询中计算出YTD和以前的YTD?

我尝试计算体重和体重ytd。我并没有理解如何在同一查询中添加先前ytd的计算。

  • 年初至今:从1月1日到今天的总权重
  • 年初至今:总和 从去年1月1日到今天的重量减去1年


SELECT SUM(CASE
                   WHEN convert(date,s.Delivery_Year+'-'+ s.Delivery_month+'-'+ s.Delivery_day) BETWEEN dateadd(yy, DATEDIFF(yy, 0, GETDATE()), 0) AND GETDATE() THEN s.Weight
                   ELSE 0
               END) AS WeightYTD ,
           sum(Weight) AS weight ,
           [Sales_Organization] ,
           [Market_Grp] ,
           [Delivery_Year] ,
           [Delivery_month] ,
           Delivery_day
    FROM Fact_sales s
    GROUP BY ,
                      [Sales_Organization] ,
                      [Market_Grp] ,
                      [Delivery_Year] ,
                      [Delivery_month] ,
                      Delivery_day

1 个答案:

答案 0 :(得分:0)

对于您真正想要的结果/行为还不清楚。

一种可能的解释是,“迄今为止”是相对于表中的日期,而不是相对于“ today” / GETDATE()

所以...

  • 对于14th March 2018:YTD = 1st Jan 201814th March 2018
  • 对于20th March 2019:YTD = 1st Jan 201920th March 2019

在这种情况下,我将执行以下操作以获取YTD列...

WITH
    grouped_by_date AS
(
    SELECT
        [Sales_Organization],
        [Market_Grp],
        [Delivery_Year],
        [Delivery_Month],
        [Delivery_Day],
        SUM([Weight])             AS Weight
    FROM
        Fact_sales s
    GROUP BY
        [Sales_Organization],
        [Market_Grp],
        [Delivery_Year],
        [Delivery_Month],
        [Delivery_Day]
),
    cumulative_sum_for_ytd AS
(
    SELECT
        *,
        SUM([Weight]) OVER (PARTITION BY [Delivery_Year]
                                ORDER BY [Delivery_Month], [Delivery_Day]
                           )
                              AS Weight_YTD
    FROM
        grouped_by_date
),

SQL Server 2008中没有LAG()函数,但是可以模拟它的“骇客技巧” ...

    hack_to_do_lag AS
(
    SELECT
        *,
        CASE
            WHEN [Delivery_Year]%2=1
            THEN MAX(CASE WHEN [Delivery_Year]%2=0 THEN [Weight_YTD] END) OVER (PARTITION BY ([Delivery_Year]+0)/2)
            ELSE MAX(CASE WHEN [Delivery_Year]%2=1 THEN [Weight_YTD] END) OVER (PARTITION BY ([Delivery_Year]+1)/2)
        END
            AS Weight_PreviousYTD
    FROM
        cumulative_sum_for_ytd
)
SELECT
    *
FROM
    hack_to_do_lag