[英]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. 我正在尝试加入3个表格,以按一年中规定的次数显示前10种药物。
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. 鉴于您要执行的操作, OBSDATE
在SELECT
没有用途。 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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.