SQL Server - 积压记录

时间:2016-04-12 13:43:12

标签: sql-server

我的表格('行动')结构&记录如下:

Action_ID   Open_date           Close_date
---------       -----------------------         -----------------------
ACT1001     2015-06-18 03:58:08.000     NULL
ACT1002     2015-06-28 06:01:10.000     2015-06-30 10:11:21.000
ACT1003     2015-07-08 01:40:19.000     2015-07-09 00:29:53.000
ACT1004     2015-07-09 04:32:00.000     NULL
ACT1005     2015-07-08 21:56:20.000     2015-07-09 01:12:37.000
ACT1006     2015-07-16 17:45:56.000     2015-08-15 23:24:35.000             
ACT1007     2015-08-05 17:54:25.000     NULL
ACT1008     2015-08-30 08:29:57.000     2015-08-30 22:11:45.000
ACT1009     2015-08-28 04:17:42.000     2015-09-11 21:39:11.000             
ACT1010     2015-09-16 07:00:01.000     2015-09-16 19:11:29.000

基于上述'行动'表,我开发了一个矩阵(计数)报告如下:

YEAR    MONTH   BACKLOG OPENED_ACTIONS  CLOSED_ACTIONS  STILL_OPEN
----    -----   ------- --------------  --------------  ----------
2015    6   0   2       1       1
2015    7   1   4       2       3
2015    8   3   3       2       4
2015    9   4   1       2       3

现在,我正在尝试为每个&找到BACKLOG记录。每个月。 我的结果如下:

YEAR    MONTH   BACKLOG_ACTIONS
----    -----   ---------------
2015    6   NULL            
2015    7   ACT1002         
2015    8   ACT1002
2015    8   ACT1004
2015    8   ACT1006         
2015    9   ACT1002
2015    9   ACT1004
2015    9   ACT1007
2015    9   ACT1009

有人可以帮助我使用MS SQL Server为上述结果编写SQL吗?

提前致谢。

1 个答案:

答案 0 :(得分:1)

/*
1) Load the activity months to a cte. MONTHNUM codes for reporting over calender years
2) Join the open actions
note:- if there is no activity in a calender month the output will not  
produce anything for that month. 
If you have a dates table in your DB it might be better to use that as
the driver rather than ACTIONS.
 */

;WITH CTE AS
(
SELECT YEAR(OPEN_DATE) CCYY, MONTH(OPEN_DATE) MM,YEAR(OPEN_DATE) * 12 + MONTH(OPEN_DATE) MONTHNUM
FROM    ACTIONS
GROUP   BY yEAR(OPEN_DATE),MONTH(OPEN_DATE),YEAR(OPEN_DATE) * 12 + MONTH(OPEN_DATE)
)
SELECT   CCYY,MM,MONTHNUM,A.*
FROM    CTE  
LEFT JOIN   ACTIONS A ON YEAR(A.OPEN_DATE) * 12 + MONTH(A.OPEN_DATE) < MONTHNUM 
WHERE   A.CLOSE_DATE IS NULL