Hey guys,
I am stuck trying to figure out how to combine several queries into one master query. First here is my main query:
Code:
SELECT A.AGTY_SYS_CD, A.BENEF_STAT_CD,
sum(case when A.RECIP_RETIR_DT <= '2010-04-01' then 1 end) AS "TOTAL RETIREES",
sum(case when recip_retir_dt2 = '2010-05-01' and A.BENEF_SEQ_NBR = 1 then 1 end) AS "NEW DROPS",
sum(case when A.BENEF_STAT_CD = 'AC' and RECIP_TYPE_CD in ('10') and RECIP_RETIR_DT BETWEEN '2010-03-01' and '2010-03-30' then 1 end) AS "A&S RETIREES",
sum(case When RIGHT (VOUCHER_ID_CD,1) = 'D' and A.RECIP_RETIR_DT BETWEEN '2010-03-01' and '2010-03-30' then 1 end) AS "DISABILITIES"
FROM DSNP.PR01_T_RECIP_SYS A,
DSNP.PR01_T_ANTY_PYMT B
WHERE A.RECIP_SSN_NBR=B.RECIP_SSN_NBR
AND A.BENEF_STAT_CD IN ('AC', 'DP')
AND A.RECIP_TYPE_CD = '10' AND A.`BENEF_SEQ_NBR = 1
GROUP BY A.AGTY_SYS_CD, A.BENEF_STAT_CD
ORDER BY 3 DESC
I discovered this week that I have to base my search criteria on a different field being min(anty_pymt_dt) = '2010-05-01 instead of retire date for these categories. This causes a problem because I have to use a derived table with the min function.
So for disabilities, the code is
Code:
SELECT count(A.recip_ssn_nbr) as "DISABILITIES" FROM
(SELECT A.recip_ssn_nbr FROM
dsnp.pr01_t_anty_pymt A,
dsnp.pr01_t_recip_sys B
where A.recip_ssn_nbr = B.recip_ssn_nbr
and right(B.voucher_id_cd,1) = 'D'
group by A.recip_ssn_nbr
having min(A.anty_pymt_dt) = '2010-05-01') as A
Is there any way I can plug this code into my CASE statement?
The other way I was thinking was to make each category a derived table, but I don't know how to perform multiple inner joins. I tried a test UNION with this query:
Code:
SELECT count(A.recip_ssn_nbr) as "DISABILITIES" FROM
(SELECT A.recip_ssn_nbr FROM
dsnp.pr01_t_anty_pymt A,
dsnp.pr01_t_recip_sys B
where A.recip_ssn_nbr = B.recip_ssn_nbr
and right(B.voucher_id_cd,1) = 'D'
group by A.recip_ssn_nbr
having min(A.anty_pymt_dt) = '2010-05-01') as A
UNION ALL
SELECT count(A.recip_ssn_nbr) as "TOTAL RETIREES"
FROM
(SELECT *
FROM DSNP.PR01_T_RECIP_SYS
WHERE RECIP_RETIR_DT <= '2010-04-01'
AND BENEF_STAT_CD IN ('AC', 'DP')
AND RECIP_TYPE_CD = '10'
AND BENEF_SEQ_NBR = 1
) as A
However, the output doesn't give me different column names. It only shows Disabilities as the column name.
Can anyone help? Thanks!