したがって、私の最初のステップは、これらのテーブルを集計することでした。最終結果の表を作成するために、問題を 2 つの部分に分割しました。最初の部分は 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