Reputation: 49
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
Where am I going wrong in the Joins to get the result I am trying to display.
Thanks! - Ann
Upvotes: 0
Views: 464
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.Upvotes: 1
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