简体   繁体   中英

Using inner join to get column data from multiple tables

I am having trouble running a query. I am trying to join 3 tables to displays the top 10 medications by the amount of times that were prescribed in a single year.

When I run it as is I get an error message about something is wrong in either the aggregate or the Select.

This is my query:

 Select Count(MED_ID), MEDICATIONS.MEDICATION_NAME, ENCOUNTER.OBSDATE 
 From MEDICATIONS
 Inner JOIN ENC_MEDICATIONS On ENC_MEDICATIONS.MED_ID = MEDICATIONS.MED_ID
 Inner JOIN ENCOUNTER On ENC_MEDICATIONS.ENC_ID = ENCOUNTER.ENC_ID
 WHERE OBSDATE Between '01/01/2011' And '12/31/2011'
 GROUP BY (MEDICATION_NAME)
 ORDER BY COUNT(MED_ID) DESC 

Then this is my table model: 在此处输入图片说明

Where am I going wrong in the Joins to get the result I am trying to display.

Thanks! - Ann

I believe you are looking for:

select Count(MED_ID), m.MEDICATION_NAME
from MEDICATIONS m Inner join
     ENC_MEDICATIONS em
     on em.MED_ID = m.MED_ID Inner JOIN
     ENCOUNTER e
     on em.ENC_ID = e.ENC_ID
where e.OBSDATE Between '2011-01-01' and '2011-12-31'
group by m.MEDICATION_NAME
order by COUNT(MED_ID) DESC 
limit 10;

Notes:

  • OBSDATE has no purpose in the SELECT , given what you want to do.
  • Date formats should use ISO/ANSI standards. YYYY-MM-DD is the most readable such format.
  • Use table aliases!
  • Qualify all column names!

Admittedly without testing it, you need to add the group by of the second non-aggregate:

 Select MEDICATIONS.MEDICATION_NAME, ENCOUNTER.OBSDATE, Count(enc_medications.MED_ID)
     From MEDICATIONS
     Inner JOIN ENC_MEDICATIONS On ENC_MEDICATIONS.MED_ID = MEDICATIONS.MED_ID
     Inner JOIN ENCOUNTER On ENC_MEDICATIONS.ENC_ID = ENCOUNTER.ENC_ID
     WHERE OBSDATE Between '01/01/2011' And '12/31/2011'
     GROUP BY medications.MEDICATION_NAME, encounter.obsdate
     ORDER BY COUNT(enc_medications.MED_ID) DESC;

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