我有下表:
的患者
ID
命名
diagnosis_id
我需要做的是让所有患有N最常见诊断的患者
我使用这个查询什么都没得到:
SELECT name FROM patients
WHERE diagnosis_id IN
(SELECT TOP(5) COUNT(diagnosis_id) FROM patients
GROUP BY diagnosis_id
ORDER BY diagnosis_id)
如何解决?
答案 0 :(得分:3)
SELECT name FROM patients
WHERE diagnosis_id IN
(
SELECT TOP(5) diagnosis_id FROM patients
GROUP BY diagnosis_id
ORDER BY COUNT(diagnosis_id) desc
)
答案 1 :(得分:1)
这有几个问题:
首先,我recommend using a common table expression进行“前5”查找而不是子查询 - 对我来说,它使它更清晰一点,虽然这里没关系,但它可能会更好真实的工作情况。
但主要的问题是,您是按诊断ID而不是计数排序前5位查找。您需要改为ORDER BY COUNT(diagnosis_id)
。
答案 2 :(得分:0)
select p.name from patients p
inner join (
select top 5 diagnosis_id, count(*) as diagnosis_count
from patients
group by diagnosis_id
order by diagnosis_count) t on t.diagnosis_id = p.diagnosis_id
答案 3 :(得分:0)
试试这个:
SELECT name FROM patients
WHERE diagnosis_id IN
(SELECT TOP(5) diagnosis_id FROM patients
GROUP BY diagnosis_id
ORDER BY COUNT(diagnosis_id))