Sunday, August 3, 2014

Use of SUM and COUNT with GROUP BY

All,


I have a set like below:



State DOB StartDt EndDt Desc Category MemberID SubID Code
NC 2003-01-30 2014-01-01 2014-01-31 Child B 123456 2 38
NC 2003-01-30 2014-01-01 2014-01-31 Child B 123456 2 39

NC 2003-01-30 2014-02-01 2014-05-31 Child B 123456 2 38
NC 2003-01-30 2014-02-01 2014-05-31 Child B 123456 2 39

NC 2003-01-30 2014-06-01 2014-07-31 Child B 123456 2 38
NC 2003-01-30 2014-06-01 2014-07-31 Child B 123456 2 39

NC 2014-01-17 2014-01-01 2014-07-31 Infant S 456789 1 49
NC 2014-02-04 2014-02-01 2014-07-31 Infant S 246376 3 49

-- MemberID and SubID identify 1 member
-- Member 123456 has 2 distinct "Code" i.e. 38,39 but each code has different "StartDt" and "EndDt"

-- Expected Result

State Desc Category CountOfDistinctCode TotalMonthsEnrolled
NC Child B 2 (38 and 39 for same member) 7 months (1 + 4 + 2) (Difference between StartDt and EndDt:1 (1/31/2014 - 1/1/2014) + 4 (5/31/2014 - 2/1/2014).. )
NC Infant S 2 (Same code 49 but different member) 13 months (7+6) (7/31/2014 - 1/1/2014 = 7 months + 7/31/2014 - 2/1/2014 = 6 months)



I tried doing a count of distinct Code and the summing up the member months, grouped by State, Desc, Category, but I am not able to get 2 and 7 for child, it somehow calculates Months as 14 (7+7). Please let me know what you guys suggest.

No comments:

Post a Comment