Ann K
Ann K

Reputation: 49

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: enter image description here

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

Thanks! - Ann

Upvotes: 0

Views: 464

Answers (2)

Gordon Linoff
Gordon Linoff

Reputation: 1269503

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!

Upvotes: 1

Hatt
Hatt

Reputation: 709

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;

Upvotes: 0

Related Questions