2017-02-21 142 views
0

我在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 

回答

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 

希望日在为你工作。

+0

谢谢nscheaffer,它的工作部分,U可以从结果表明白,不同的项目有来自行号一个重新开始,你能不能帮我请。 查询下面给出了部分结果 –

+1

我错过了。您只需要添加每个LEFT JOIN条件,以便从每个表中设置相同的ProjectID,但看起来您已经知道了这一点。工作很好。 – nscheaffer

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 

上面的查询完全适用于我的表

相关问题