I tried a lot, seperated the query to several groups, but I have not got the desired result until now, and here are the layout of the report, the first page is the detail listing, the second page is a sub total according to each facility, and the third page is the total for all facilities,
This is the query:
Select oms.offender_id,
vhb.last_name,
vhb.first_name,
vhb.liv_unit_desc,
hc.description,
oms.comment_text,
lvl1.LIVING_UNIT_ID lvl1_unit_id,
lvl1.DESCRIPTION lvl1_desc,
lvl1.AGY_LOC_ID,
hc.description diet_order
From offender_medical_services oms,
v_header_block vhb,
hcpcs_codes hc,
(SELECT LIVING_UNIT_ID,
DESCRIPTION,
AGY_LOC_ID
FROM LIVING_UNITS
WHERE LIVING_UNIT_TYPE = (SELECT HOUSING_LEV_1_CODE
FROM AGENCY_LOCATIONS
WHERE AGENCY_LOCATIONS.AGY_LOC_ID = LIVING_UNITS.AGY_LOC_ID
AND AGENCY_LOCATIONS.AGENCY_LOCATION_TYPE = 'INST'
AND AGENCY_LOCATIONS.AGY_LOC_ID IN (SELECT AGY_LOC_ID
FROM CASELOAD_AGENCY_LOCATIONS
WHERE CASELOAD_ID = :CASELOAD) )) lvl1
Where oms.medical_service_code = hc.hcpcs_code
And oms.offender_id = vhb.root_offender_id
And oms.active_flag = 'Y'
And oms.end_date is null
And vhb.agy_loc_id = lvl1.agy_loc_id
And vhb.active_flag = 'Y'
And vhb.root_offender_id in (
select root_offender_id
from v_header_block
where living_unit_id in (select living_unit_id from living_units
start with living_unit_id = lvl1.living_unit_id
connect by prior living_unit_id = parent_living_unit_id )
)
&CF_DIET_FLAG
ORDER BY lvl1.AGY_LOC_ID, oms.offender_id
Please help me take a look, cause I tried a lot, there is still such a mess.
Thanks a lot!