SQL - 接下来十二个月的平均值

SQL - Next Twelve Months Average

我正在尝试计算未来十二个月的平均值。

我计算了一个取决于我们要查看的月份的因子:

365-DATEPART(dy,'2017-06-26')/365  & 1-365-DATEPART(dy,'2017-06-26')/365 

我已经能够为指定的 Date_Month 获得所需的答案,但我希望能够 trim 它(删除包含 NULL 的空值)并使其可以应用大量 Date_Months.

这是当前输出:

Company_Id  Sales   Date_Year   Date_Month  NTMA_Factor Sales_Down  Sales_Up    NTMA_Sales
        1   675.051     2014    2013-03-31  0.7534      675.051     NULL        NULL
        2   47946.200   2014    2013-03-31  0.7534      47946.200   50364.200   48542.4788000
        2   50364.200   2015    2013-03-31  0.7534      50364.200   NULL        NULL
        3   6891.430    2014    2013-03-31  0.7534      6891.430    6917.450    6897.8465320
        3   6917.450    2015    2013-03-31  0.7534      6917.450    NULL        NULL
        5   2190.140    2014    2013-03-31  0.7534      2190.140    2318.250    2221.7319260
        5   2318.250    2015    2013-03-31  0.7534      2318.250    NULL        NULL

有没有办法在 SQL 中为更大的 Date_Month 组执行此操作?

目前查询:

SELECT top 7
    S.Company_Id
    , S.Sales
    , Y.Date_Year
    , M.Date_Month
    , N.NTMA_Factor
    , (S.Sales) AS Sales_Down
    , (LEAD(S.Sales, 1) OVER (Partition by S.Company_Id ORDER BY Y.Date_Year ASC)) AS Sales_Up
    , ((S.Sales * N.NTMA_Factor)  + (LEAD(S.Sales, 1) OVER (Partition by S.Company_Id ORDER BY Y.Date_Year ASC))*(1-NTMA_Factor)) As NTMA_Sales 
FROM Sales AS S
      INNER JOIN Date_Year AS Y ON Y.Date_Year_Id = S.Date_Year_Id
      INNER JOIN Date_Month AS M ON M.Date_Month_Id = S.Date_Month_Id
      INNER JOIN NTMA_Factor AS N ON N.Date_Month_Id = M.Date_Month_Id
where
    Date_Year in (2014,2015, 2013) and Date_Month in ('2013-03-31');

理想情况下,我希望获得完全相同的输出,但删除包含 NULL 的行并可以查看更多 Date_Months(这意味着更改 Lead & Over 语句,这样它们就不会采取下面的第一个,因为它现在看起来是这样做的)。我还想删除最后的 Sales_Down & Sales_Up 列,但这似乎不是问题。

我正在使用 Microsoft SQL Server Management Studio 并且很遗憾 SQL 中的函数是新手。

谢谢。

如果我正确解释了你的问题(不确定),你可以使用 LEAD() function with the OVER() 子句,例如:

SELECT
      S.Sales
    , Y.Date_Year
    , M.Date_Month
    , N.NTMA_Factor
    , (S.Sales * N.NTMA_Factor) AS NTMA_Sales_Down
    , LEAD(S.Sales, 1) OVER (ORDER BY Y.Date_Year ASC) AS SalesNextYear
FROM Sales AS S
      INNER JOIN Date_Year AS Y ON Y.Date_Year_Id = S.Date_Year_Id
      INNER JOIN Date_Month AS M ON M.Date_Month_Id = S.Date_Month_Id
      INNER JOIN NTMA_Factor AS N ON N.Date_Month_Id = M.Date_Month_Id
;

LEAD 和 LAG 函数允许您跨行 "look forward"(领先)或 "look backward"(滞后),我认为这就是您正在寻找的功能。 OVER 子句提供 "controls" 函数的操作方式。在这种情况下,需要按年份排序。

nb:有一系列非常有用的 "analytic" 函数也需要或可以使用 over 子句。例如 SUM() OVER() 可以提供 运行 总数,或者 ROW_NUMBER() OVER() 对于返回 first/last/earliest/latest 行

特别有用