SQL YTD和去年YTD的完整数据

时间:2017-07-17 14:46:22

标签: sql sql-server

我需要在桌面上计算YTD和去年的YTD [SQL Server 2012]。以下是我试过的查询。在某些情况下它会增加一倍和三倍。

SELECT SUM(A.RevisionNumber)YTD,SUM(P.RevisionNumber)LY_YTD,B.OrderDateM,B.OrderDateY
FROM
    (select MONTH(OrderDate)OrderDateM,YEAR(OrderDate)OrderDateY from sales.SalesOrderHeader B
    group by MONTH(OrderDate),YEAR(OrderDate))B
 LEFT JOIN
    (select SUM(RevisionNumber)RevisionNumber,MONTH(OrderDate)OrderDateM,YEAR(OrderDate)OrderDateY
    from sales.SalesOrderHeader
    group by MONTH(OrderDate),YEAR(OrderDate))A
 ON A.OrderDateM<=B.OrderDateM AND A.OrderDateY=B.OrderDateY
 LEFT JOIN
    (select SUM(RevisionNumber)RevisionNumber,MONTH(OrderDate)OrderDateM,YEAR(OrderDate)OrderDateY
    from sales.SalesOrderHeader
    group by MONTH(OrderDate),YEAR(OrderDate))P
 ON P.OrderDateM<=B.OrderDateM AND P.OrderDateY=B.OrderDateY-1
GROUP BY B.OrderDateM,B.OrderDateY
ORDER BY B.OrderDateY,B.OrderDateM

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以使用如下窗口功能:

;With cte as (
    Select Sum(RevisionNumber) As SM_RevisionNumber, Month(OrderDate) as OrderM,
           Year(OrderDate) as OrderY
           From Sales.SalesOrderHeader
           Group by Month(OrderDate), Year(OrderDate)
        ), cte2 as (
    Select YTD = Sum(SM_RevisionNumber) over (partition by OrderY order by OrderM),
        OrderM, OrderY, RowN = Row_Number() over(order by OrderY, OrderM)
        from cte
    )
    Select YTD, LY_YTD = lag(YTD, 12, null) over(Order by RowN), OrderM, ORderY
        from cte2

但是这个解决方案假设我们每个月和每年至少有一个条目。