Quantcast
Channel: SQLServerCentral » SQL Server 2014 » Development - SQL Server 2014 » Latest topics
Viewing all articles
Browse latest Browse all 3145

Backlog records using MS Sql

$
0
0
I have a table 'Actions' like this.CREATE TABLE Actions ( Action_Id varchar(25) NOT NULL PRIMARY KEY, Open_Dt datetime NULL, Close_Dt datetime NULL);INSERT INTO Actions (Action_Id, Open_Dt, Close_Dt) VALUES ('ACT1001', '2015-06-18 03:58:08.000', NULL);INSERT INTO Actions (Action_Id, Open_Dt, Close_Dt) VALUES ('ACT1002', '2015-06-28 06:01:10.000', '2015-06-30 10:10:10.000');INSERT INTO Actions (Action_Id, Open_Dt, Close_Dt) VALUES ('ACT1003', '2015-07-08 01:40:19.000', '2015-07-09 10:10:10.000');INSERT INTO Actions (Action_Id, Open_Dt, Close_Dt) VALUES ('ACT1004', '2015-07-09 04:32:00.000', NULL);INSERT INTO Actions (Action_Id, Open_Dt, Close_Dt) VALUES ('ACT1005', '2015-07-08 21:56:20.000', '2015-07-09 10:10:10.000');INSERT INTO Actions (Action_Id, Open_Dt, Close_Dt) VALUES ('ACT1006', '2015-07-16 17:45:56.000', '2015-08-15 10:10:10.000');INSERT INTO Actions (Action_Id, Open_Dt, Close_Dt) VALUES ('ACT1007', '2015-08-05 17:54:25.000', NULL);INSERT INTO Actions (Action_Id, Open_Dt, Close_Dt) VALUES ('ACT1008', '2015-08-30 08:29:57.000', '2015-08-30 10:10:10.000');INSERT INTO Actions (Action_Id, Open_Dt, Close_Dt) VALUES ('ACT1009', '2015-08-28 04:17:42.000', '2015-09-11 10:10:10.000');INSERT INTO Actions (Action_Id, Open_Dt, Close_Dt) VALUES ('ACT1010', '2015-09-16 07:00:01.000', '2015-09-16 10:10:10.000');Based on the above 'Actions' table, I developed a matrix (counts) report as below: YEAR MONTH BACKLOG OPENED_ACTIONS CLOSED_ACTIONS STILL_OPEN---- ----- ------- -------------- -------------- ----------2015 6 0 2 1 12015 7 1 4 2 32015 8 3 3 2 42015 9 4 1 2 3Now, I am trying to find BACKLOG records for each & every month. My results should be as below:YEAR MONTH BACKLOG_ACTIONS---- ----- ---------------2015 6 NULL2015 7 ACT10022015 8 ACT10022015 8 ACT10042015 8 ACT10062015 9 ACT10022015 9 ACT10042015 9 ACT10072015 9 ACT1009I have tried like this:;WITH CTE AS(SELECT YEAR(OPEN_Dt) CCYY, MONTH(OPEN_Dt) MM, YEAR(OPEN_Dt) * 12 + MONTH(OPEN_Dt) MONTHNUMFROM ACTIONSGROUP BY YEAR(OPEN_Dt), MONTH(OPEN_Dt),YEAR(OPEN_Dt) * 12 + MONTH(OPEN_Dt))SELECT CCYY, MM, A.Action_IdFROM CTE LEFT JOIN ACTIONS A ON YEAR(A.OPEN_Dt) * 12 + MONTH(A.OPEN_Dt) < MONTHNUM WHERE A.CLOSE_Dt IS NULLBut it is not working properly. Can someone help me with writing the SQL for the above result using MS SQL Server?Thanks in advance.

Viewing all articles
Browse latest Browse all 3145

Trending Articles