简体   繁体   English

SQL | 聚合

[英]SQL | Aggregation

My objective is to get a table such as this: 我的目标是得到一个这样的表:
Request: 请求:
Wards where the annual cost of drugs prescribed exceeds 25 年度处方药费用超过25的病房

ward_no | year | cost      
     w2 | 2007 | 34  
     w4 | 2007 | 160  
     w5 | 2006 | 26  
     w5 | 2007 | 33 

I would input a picture but lack reputation points. 我会输入图片,但缺乏信誉点。

Here is what I have done so far: 到目前为止,这是我所做的:

select      w.ward_no,
            year(pn.start_date)     as year,
            pn.quantity * d.price   as cost
from        ward w,
            patient pt,
            prescription pn,
            drug d
where       w.ward_no = pt.ward_no
        and
            pn.drug_code = d.drug_code
        and 
            pn.patient_id = pt.patient_id
group by    w.ward_no, 
            year,
            cost
having      cost > 25
order by    w.ward_no, year

My current output is such: 我当前的输出是这样的:

    ward_no|year|cost
    'w2'   |2006|0.28
    'w2'   |2007|3.20
    'w2'   |2007|9.50
    'w2'   |2007|21.60
    'w3'   |2006|10.08
    'w3'   |2007|4.80
    'w4'   |2006|4.41
    'w4'   |2007|101.00
    'w4'   |2007|58.80
    'w5'   |2006|25.20
    'w5'   |2006|0.56
    'w5'   |2007|20.16
    'w5'   |2007|12.60

How would I reduce each ward_no to have only a single row of year (say 2006 or 2007) instead of having x of them? 我如何将每个ward_no减少为仅一行(例如2006或2007)而不是x?
Any help would be very much appreciated I am really stuck and have no clue what to do. 任何帮助将不胜感激,我真的很困并且不知道该怎么办。

You are grouping by cost, so each cost gets a new line. 您正在按成本分组,因此每个成本都有一个新行。 Remove the cost from your grouping 从分组中删除费用

select      w.ward_no,
        year(pn.start_date)     as year,
        avg(pn.quantity * d.price)   as cost
from        ward w,
        patient pt,
        prescription pn,
        drug d
where       w.ward_no = pt.ward_no
    and
        pn.drug_code = d.drug_code
    and 
        pn.patient_id = pt.patient_id
group by    w.ward_no, 
        year
having       avg(pn.quantity * d.price) > 25
order by    w.ward_no, year

You need to group by ward and year, and sum up the costs: 您需要按病房和年份分组,并汇总费用:

select w.ward_no,
       year(pn.start_date) as year,
       sum(pn.quantity * d.price) as cost
  from ward w
  inner join patient pt
    on pt.ward_no = w.ward_no
  inner join prescription pn
    on pn.patient_id = pt.patient_id
  inner join drug d
    on d.drug_code = pn.drug_code
  group by w.ward_no, 
           year(pn.start_date)
  having sum(pn.quantity * d.price) > 25
  order by w.ward_no, year

What flavor of SQL is this supposed to be for? 这应该用于哪种SQL?

Share and enjoy. 分享并享受。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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