所以我的第一步是聚合這些表。爲了實現我的最終結果表,我將問題分爲兩部分。第一部分是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
我的意思是它的明顯的和(total_paid)我更關心的COUNT(IF(PHID ==真???)(邏輯非語法)其中Total_Paid爲空?IDK我希望它是準確的。 – Hituptony 2012-08-01 19:50:19