我有一个简单的查询。
select id, patient_id, diagnosis from dbo.diabetes_rx_tracker
group by id, patient_id, diagnosis
最常见的诊断代码需要显示在列表顶部并带有计数。
我尝试使用计数功能。
但它会将每位患者的所有值都返回为1而不是添加。
select id, patient_id, count(diagnosis) from dbo.diabetes_rx_tracker
group by id, patient_id, diagnosis
在编辑我的小组时,我也一直在抛出错误。
任何帮助将不胜感激。谢谢。
答案 0 :(得分:9)
这看起来好像你没有足够的聚合。 GROUP by中的每个字段代表一个总计与其他字段聚合的字段。所以这只会通过id,病人和诊断向你展示诊断。不是很有帮助。
要获得最常见的诊断期,请从分组中删除id和patient_id:
select
count(diagnosis)
from dbo.diabetes_rx_tracker
group by
diagnosis
order by
count(diagnosis) desc
要获取所有ID中最常见的代码,请从分组中删除patient_id并选择:
select
diagnosis,
id,
count(1) as CodeCount
from dbo.diabetes_rx_tracker
group by
diagnosis,
id
order by
count(diagnosis) desc
更新:根据您的新条件,这就是您想要的。
select
id,
diagnosis,
ct
from (
select
row_number() OVER (PARTITION BY id ORDER BY count(diagnosis) desc ) as rn,
count(diagnosis) as ct,
diagnosis,
id
from dbo.diabetes_rx_tracker
group by
id,
diagnosis
) ranked
where
rn = 1
order by
CT desc