Erland,
This still gives me "14" months for "Child" (should be "7"). Below's the code that I have. For the periods taht you specified, I'll need the result to be 2, since the member was active in Feb as well as March.
IF OBJECT_ID('tempdb..#Test') IS NOT NULL DROP TABLE #Test
GO
DECLARE @LastDayOfPrevYear DATE = (SELECT CONVERT(DATE,DATEADD(yy, DATEDIFF(yy,0,getdate()) + 1, -1)))
DECLARE @LastDayOfPrevMonth DATE = (SELECT CONVERT(DATE,DATEADD(MONTH, DATEDIFF(MONTH, -1, GETDATE())-1, -1)))
CREATE TABLE #Test
(
[State] CHAR(2),
DOB DATE,
StartDt DATE,
EndDt DATE,
[Desc] VARCHAR(8),
Category CHAR(1),
MemberID VARCHAR(10),
SubID VARCHAR(2),
Code VARCHAR(5)
)
INSERT INTO #Test
VALUES
('NC','1/30/2013','1/1/2014','1/31/2014','Child','B','123456','2','38'),
('NC','1/30/2013','1/1/2014','1/31/2014','Child','B','123456','2','39'),
('NC','1/30/2013','2/1/2014','5/31/2014','Child','B','123456','2','38'),
('NC','1/30/2013','2/1/2014','5/31/2014','Child','B','123456','2','39'),
('NC','1/30/2013','6/1/2014','7/31/2014','Child','B','123456','2','38'),
('NC','1/30/2013','6/1/2014','7/31/2014','Child','B','123456','2','39'),
('NC','1/17/2014','1/1/2014','7/31/2014','Infant','S','456789','1','49'),
('NC','2/4/2014','2/1/2014','7/31/2014','Infant','S','246376','3','49')
SELECT
[State]
, [Desc]
, Category
, COUNT(DISTINCT str(MemberID) + str(SubId) + str(Code)) AS TotalCnt
, SUM(DATEDIFF(MONTH, StartDt, DATEADD(DAY, 1, EndDt))) AS Months
, SUM
(DATEDIFF(MONTH, StartDt,
CASE
WHEN EndDt >= @LastDayOfPrevYear
THEN @LastDayOfPrevMonth
ELSE EndDt
END) + 1) AS CalMonths -- This is what I have
FROM #Test
GROUP BY
[State]
, [Desc]
, Category
No comments:
Post a Comment