0

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

1
  • 1
    You're missing the 3rd select/2nd non aggregated field in your group by statement. Commented May 11, 2018 at 18:12

2 Answers 2

1

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!
Sign up to request clarification or add additional context in comments.

1 Comment

This worked thank you! I am a beginner, just learning how to write queries so thank you for all the tips!
0

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;

6 Comments

Did the query end up running?
Tried it out, no go, gives same type of error message.
There was a comma in the answer I just took out which would throw an error - otherwise the syntax should be ok now.
I saw that, I took it out and tried it again but still throwing error.
Oh I think its an alias for med_id - you're counting it without an alias but it shows up in two tables you selected.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.