简体   繁体   中英

Display results in SQL that meet the criteria

select only those top 10 hospitals that have both kinds of ICU and SICU beds, ie only hospitals that have at least 1 ICU bed and at least 1 SICU bed can be included in this part of the analysis. Here is what I have so far

select bu.business_name as 'Hospital Name'
,sum(be.license_beds) as Total_Licenses
,case when be.bed_id = 4 then 'ICU' end as "ICU"
,case when be.bed_id = 15 then 'SICU' end as "SICU"
from bed_fact be 
join bed_type bt 
  on be.bed_id = bt.bed_id
join business bu 
  on be.ims_org_id = bu.ims_org_id
where be.bed_id = 4 
    or be.bed_id = 15
and be.license_beds IS NOT NULL
group 
    by bu.business_name
order 
    by Total_Licenses DESC
limit 10
;

I need to some how only count the hospital that has at least one of ICU or SICU value

You want conditional aggregation and a having clause:

select 
    bu.business_name as Hospital_Name,
    sum(be.license_beds) as Total_Licenses,
    sum(be.bed_id = 4) as ICU,
    sum(be.bed_id = 15) as SICU
from bed_fact be 
inner join bed_type bt on be.bed_id = bt.bed_id
inner join business bu on be.ims_org_id = bu.ims_org_id
where be.bed_id in (4, 15) and be.license_beds is not null
group by bu.business_name
having ICU > 0 and SICU > 0
order by Total_Licenses desc
limit 10

If you don't what the counts in the resultset, then move the aggregate functions to the having clause:

select 
    bu.business_name as Hospital_Name,
    sum(be.license_beds) as Total_Licenses
from bed_fact be 
inner join bed_type bt on be.bed_id = bt.bed_id
inner join business bu on be.ims_org_id = bu.ims_org_id
where be.bed_id in (4, 15) and be.license_beds is not null
group by bu.business_name
having sum(be.bed_id = 4) > 0 and sum(be.bed_id = 15) > 0
order by Total_Licenses desc
limit 10

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM