所以我的第一步是聚合这些表。我将问题分解为两部分,以获得我的最终结果表。第一部分是 ActiveMembersPerMonth,它反映了:
month total
2004-02 5
为此,我创建了一个例程来处理分组,这就是我的存储过程的样子:
DELIMITER $$
CREATE PROCEDURE `ActiveMembersPerMonth`(sStartMonth VARCHAR(10), sEndMonth VARCHAR(10))
BEGIN
DECLARE dStartMonth DATE DEFAULT DB.ConvertYearMonthDate(sStartMonth,False);
DECLARE dEndMonth DATE DEFAULT DB.ConvertYearMonthDate(sEndMonth,True);
DECLARE curMonthStart DATE;
DECLARE curMonthEnd DATE;
DECLARE curMonthStr CHAR(7);
TRUNCATE DB.ActiveMembersPerMonth_;
SET curMonthStart = dStartMonth;
WHILE curMonthStart<=dEndMonth DO
SET curMonthEnd = LAST_DAY(curMonthStart);
SET curMonthStr = date_format(curMonthStart,'%Y-%m');
INSERT INTO DB.ActiveMembersPerMonth
SELECT eh.SCC, eh.PHID, eh.SID, eh.CID, eh.CGID, curMonthStr,count(*),sum(IF(m.membership='Employee',1,0)),
sum(IF(m.membership<>'Employee',1,0)),null
from DB.table_SIHO eh
join DB.Membership m on eh.SCC=m.SCC and eh.PHID=m.PHID
and eh.SID=m.SID
WHERE eh.Enroll_Date<=curMonthStart AND (eh.Disenroll_Date>curMonthEnd OR eh.Disenroll_Date IS NULL)
GROUP BY SCC, CID, CGID, curMonthStr;
SET curMonthStart = curMonthStart + INTERVAL 1 MONTH;
END WHILE;
END;
call ActiveMembersPerMonth_SIHO('2006-01-01', '2012-05-31')
问题的下一部分是让 total_Paid 和相关的月份与我现在拥有的相匹配......这是:
Active_Total Month
5 2006-02
现在我有另一个表聚合,其中包含月份和 total_paid 所以我将把这些与从我的存储过程创建的月份和 active_Total 结合起来......
CREATE TABLE Rx_Paid_
SELECT CGID, date_format(DOS, '%Y-%m') as Month, SUM(Amt_Paid) as Rx_Paid FROM DB.Prescriptions
WHERE concat(Policy_HoldeR_ID, Suffix_ID) not in
('M000560838','M000029518','M00002699','M00002769') and DOS between '2006-01-01' and '2012-05-31'
group by CGID, Month;
服务也是如此 -
CREATE TABLE Services_Paid;
SELECT CGID, date_format(Serv_Beg_Date, '%Y-%m') as Month, SUM(Amt_Paid) as Services_Paid FROM DB.Services
WHERE concat(PHID, SID) not in ('M000560838','M000029518','M00002699','M00002769') and Beg_Date between '2006-01- 01' and '2012-05-31'
group by CGID, Month;
基本上我在我的小组中达到了我想要的结果。我在第一个提到的表中有 total_paid。我所要做的就是按月分组和一个标识符(ClientGroupID)(组级标识符)
CGID Month Active Service_Paid Rx_Paid
128 2006-01 314 2620.19 0.00
128 2006-02 330 4880.46 0.00
128 2006-03 344 29312.00 0.00
128 2006-04 359 15177.99 0.00
128 2006-05 386 774.58 0.00
128 2006-06 421 5966.52 0.00