如何汇总()三个月的数据,包括当月

时间:2017-02-21 11:24:58

标签: sql-server-2008 sum common-table-expression

我在SQL Server中有一个看起来像这样的表

ProjectId   BookedHours    FiscalYear  FiscalMonth
--------------------------------------------------
PRJ1        2040            2015-16     1-Apr-15
PRJ1        1816            2015-16     1-May-15
PRJ1        1760            2015-16     1-Jun-15
PRJ1        1832            2015-16     1-Jul-15
PRJ2        1752            2015-16     1-Sep-15
PRJ2        1529            2015-16     1-Oct-15
PRJ2        1336            2015-16     1-Nov-15
PRJ2        1480            2015-16     1-Dec-15
PRJ2        522             2015-16     1-Jan-16

我需要总结当前+前两个月预订时间的值,即预期结果应如下表所示

ProjectId   BookedHours    FiscalYear  FiscalMonth  ExpectedValue
-----------------------------------------------------------------
PRJ1        2040            2015-16     1-Apr-15    2040
PRJ1        1816            2015-16     1-May-15    3856
PRJ1        1760            2015-16     1-Jun-15    5616
PRJ1        1832            2015-16     1-Jul-15    5408
PRJ2        1752            2015-16     1-Sep-15    1752
PRJ2        1529            2015-16     1-Oct-15    3281   
PRJ2        1336            2015-16     1-Nov-15    4617
PRJ2        1480            2015-16     1-Dec-15    4345
PRJ2         522            2015-16     1-Jan-16    3338

2 个答案:

答案 0 :(得分:0)

这是一种方法......

WITH cte AS 
(
    SELECT 
    row_num = ROW_NUMBER() OVER(ORDER BY FiscalMonth),
    * 
    FROM dbo.Project p
)
SELECT CurrentMonth.ProjectID, CurrentMonth.BookedHours, CurrentMonth.FiscalYear, CurrentMonth.FiscalMonth, 
(CurrentMonth.BookedHours + COALESCE(OneMonthBack.BookedHours, 0) + COALESCE(TwoMonths.BookedHours, 0)) AS ExpectedValue
FROM cte CurrentMonth
LEFT JOIN cte OneMonthBack ON OneMonthBack.row_num = CurrentMonth.row_num - 1
LEFT JOIN cte TwoMonths ON TwoMonths.row_num = CurrentMonth.row_num - 2

希望对你有用。

答案 1 :(得分:0)

    WITH cte AS 
(
    SELECT *,row_num=ROW_NUMBER() OVER( PARTITION BY Projectid ORDER BY Projectid,FiscalYear,FiscalMonth)
    FROM dbo.Project p
)  

SELECT CM.ProjectID, CM.FiscalYear, CM.FiscalMonth, CM.BookedHours, 
(CM.BookedHours + COALESCE(OMB.BookedHours, 0) + COALESCE(TM.BookedHours, 0)) AS ExpectedValue
FROM cte CM
LEFT OUTER JOIN cte OMB WITH(NOLOCK) ON OMB.row_num = CM.row_num - 1 and CM.Projectid=OMB.Projectid
LEFT OUTER JOIN cte TM WITH(NOLOCK) ON TM.row_num = CM.row_num - 2 and CM.Projectid=TM.Projectid
ORDER BY CM.ProjectID, CM.FiscalYear, CM.FiscMonth ASC

以上查询适用于我的表格