SQL相应地获取过去24个月和订单月的数据

时间:2018-02-05 11:21:13

标签: sql sql-server tsql sql-server-2017

我正在使用下面的SQL,但结果并没有给出2017年1月数据结果。

我得到的结果是2月 - 12月,而不是2月 - 1月。

SELECT CSE.[CaseID],
       YEAR(CSE.[StartDate]) AS [YEAR],
       CSE.[StartDate],
       CSE.[EndDate],
       (
           SELECT dbo.[MI_GetTotalWorkingDays](CSE.[StartDate], CSE.[EndDate])
       ) AS [Days]

INTO #TMP
FROM dbo.[Case] CSE
    LEFT JOIN dbo.Employee EMP
        ON CSE.EmployeeID = EMP.EmployeeID
    LEFT JOIN dbo.Company CMP
        ON CMP.CompanyID = EMP.CompanyID
    LEFT JOIN
    (SELECT * FROM dbo.UnitNameWithParentsVM) AS DIV
        ON DIV.UnitId = EMP.UnitID
WHERE Month(CSE.[StartDate]) > month(DATEADD(MONTH, -37 , GETDATE()))
AND CMP.CompanyID = @CompanyId;

SELECT 
       YEAR(StartDate) AS [Year],
       MONTH(StartDate) AS [Month Number],
       DATENAME(MM, StartDate) AS [Month Name],
       SUM([Days]) AS [Days Lost]
INTO #PREVIOUS_YEAR
FROM #TMP
WHERE YEAR(StartDate) = YEAR(DATEADD(MONTH, -24, GETDATE()))
GROUP BY DATENAME(MM, StartDate),
         YEAR(StartDate),
         MONTH(StartDate);

SELECT 
       YEAR(StartDate) AS [Year],
       MONTH(StartDate) AS [Month Number],
       DATENAME(MM, StartDate) AS [Month Name],
       SUM([Days]) AS [Days Lost]
INTO #CURRENT_YEAR
FROM #TMP
WHERE YEAR(StartDate) = YEAR(DATEADD(MONTH, -12, GETDATE()))
GROUP BY DATENAME(MM, StartDate),
         YEAR(StartDate),
         MONTH(StartDate);

SELECT P.[Month Name],
       COALESCE(P.[Days Lost], 0) AS [Previous Year Days Lost],
       COALESCE(C.[Days Lost], 0) AS [Current Year Days Lost]
FROM #PREVIOUS_YEAR P
    LEFT JOIN #CURRENT_YEAR C
        ON P.[Month Number] = C.[Month Number]
ORDER BY 
p.[Year],
P.[Month Number];

数据样本如下,

YEAR    |StartDate  |EndDate    |Days   
2017    |05/01/2017 |NULL       |283   
2017    |11/01/2017 |NULL       |279
2017    |23/01/2017 |NULL       |271    
2017    |19/01/2017 |NULL       |273    
2017    |01/02/2017 |NULL       |264    
2017    |02/02/2017 |NULL       |263    
2017    |20/02/2017 |NULL       |251    
2017    |22/02/2017 |NULL       |249    
2017    |27/02/2017 |NULL       |246    
2017    |22/03/2017 |NULL       |229
2017    |23/03/2017 |NULL       |228

如果我回去37个月,我会得到2016年的数据,但这对我来说似乎有些奇怪。但问题是为什么2017年1月的数据没有显示

这是查询的输出

February    |475    |1515
March       |814    |1137
April       |286    |886
May         |643    |574
June        |2112   |1486
July        |572    |1119
August      |987    |312
September   |2054   |1134
October     |1587   |1645
November    |2129   |0
December    |1672   |0

可以在http://sqlfiddle.com/#!18/9e389

找到SQL小提琴

根据上述链接,我现在设法得到一个工作小提琴。

感谢任何帮助

0 个答案:

没有答案