所以我的第一步是聚合这些表。为了实现我的最终结果表,我将问题分为两部分。第一部分是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