计算SQL SERVER 2008中的日期

时间:2019-03-22 13:51:44

标签: sql tsql sql-server-2008

我正在尝试计算今天的前一年,但以前的所有年份我都得到Weight_PreviousYTD

我需要考虑其他列。我该如何修改脚本?

例如:

  

2019年3月20日:年初至今= 2018年1月1日至2018年3月20日

WITH grouped_by_date AS
  (SELECT *
   FROM factsales s
),
     cumulative_sum_for_ytd AS
  (SELECT T.*,
          T1.Weight_YTD
   FROM grouped_by_date T CROSS APPLY
     (SELECT SUM(QTY_UoM) AS Weight_YTD
      FROM grouped_by_date
      WHERE [Delivery_Year]=T.[Delivery_Year]
        AND convert(date,Delivery_Year+'-'+ Delivery_month+'-'+ [Invoicing_Day])<=convert(date,T.Delivery_Year+'-'+ t.Delivery_month+'-'+ t.[Invoicing_Day])
     and  [Sales_Organization]=T.Sales_Organization

      and[Sales_Product_Name_N3]=T.Sales_Product_Name_N3
      and[Sales_Product_Name_N2]=T.[Sales_Product_Name_N2]
      and[Sales_Product_Name_N1]=T.[Sales_Product_Name_N1]
      and[Market_Segment_Name_N2]=T.[Market_Segment_Name_N2]

      and[Doc_Currency]=T.Doc_Currency

      and[User_Name_N1]=T.User_Name_N1
      and[Engineer_Code]=T.Engineer_Code

      and[User_Name_N2]=T.User_Name_N2
      and[Bill_To_Customer_Code]=T.Bill_To_Customer_Code

      and[User_Country_Code]=T.User_Country_Code 
      and[User_N3_Country_Name]=T.User_N3_Country_Name

         ) T1),
     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

0 个答案:

没有答案