Hello @sam nick
--=======================================================================================
create table sampletable1 (keyid int not null,
datefield date,
OrderiD nvarchar(10) ,
Ord_Status nvarchar(20)
)
insert into Sampletable1 values ('1','01/01/2021','ORD_123','Pending');
insert into Sampletable1 values ('2','01/15/2021','ORD_123','Shipped');
insert into Sampletable1 values ('3','01/20/2021','ORD_123','Completed');
insert into Sampletable1 values ('4','02/04/2021','ORD_234','Shipped');
insert into Sampletable1 values ('5','03/04/2021','ORD_345','Shipped');
insert into Sampletable1 values ('6','03/10/2021','ORD_345','Completed');
insert into Sampletable1 values ('7','04/01/2021','ORD_345','Returned');
insert into Sampletable1 values ('8','04/10/2021','ORD_345','Cancelled');
insert into Sampletable1 values ('9','01/05/2021','ORD_456','Pending');
insert into Sampletable1 values ('10','01/10/2021','ORD_456','Shipped');
insert into Sampletable1 values ('11','01/20/2021','ORD_456','Completed');
insert into Sampletable1 values ('12','04/05/2021','ORD_567','Shipped');
insert into Sampletable1 values ('13','04/10/2021','ORD_678','Cancelled');
insert into Sampletable1 values ('14','03/01/2021','ORD_789','Completed');
insert into Sampletable1 values ('15','07/01/2021','ORD_890','Pending');
insert into Sampletable1 values ('16','07/04/2021','ORD_890','Shipped');
insert into Sampletable1 values ('17','07/25/2021','ORD_890','Completed');
--=======================================================================================
Please use the below query:
DECLARE @Ship _start DATETIME = '2021-01-31',
@Ship _end DATETIME = '2021-08-01';
WITH cteMonth AS
( SELECT @Ship _start AS dt
UNION ALL
SELECT DATEADD(m, 1, dt) FROM cteMonth WHERE DATEADD(m, 1, dt) < DATEADD(m, 1, @Ship _end)
),
cteAllEOMonth AS (SELECT EOMONTH(dt) AS EOM FROM cteMonth WHERE dt <= EOMONTH(@Ship _end)),
cteShipped AS (SELECT EOMONTH(datefield) AS EOM FROM Sampletable1 WHERE Ord_Status = 'Shipped')
SELECT DISTINCT M.EOM, COUNT (S.EOM) OVER (ORDER BY M.EOM) AS RunningTotal
FROM cteAllEOMonth M LEFT JOIN cteShipped S ON M.EOM = S.EOM
ORDER BY 1
----------
As per the desired result-set in the image
the first record presentation seems incorrect as you have mentioned that on 01-Jan-2021 (Start Of Month) you have 2 shipment, where-as for rest of the record you consider the End Of Month.
So i consider it is a typing mistake, hence the above query will give you result for End Of Month for the first record also. In case if if this is not a typing mistake, please let me know.