【问题标题】:Im trying to remove duplicates while getting a MAX result at the same time. I cant remove the duplicates我试图在同时获得 MAX 结果的同时删除重复项。我无法删除重复项
【发布时间】:2020-07-18 15:57:09
【问题描述】:
select distinct person.person_id, MAX(patient_encounter.enc_timestamp) as LastAppt
from patient_encounter inner join person on patient_encounter.person_id = person.person_id
where enc_timestamp between '2018-04-05 00:00:00.000' and '2020-04-05 23:59:59.999'
and patient_encounter.person_id = person.person_id
and billable_ind = 'y' and person.last_name <> 'ztest'
group by person.person_id, patient_encounter.enc_timestamp
order by person.person_id
【问题讨论】:
标签:
sql
duplicates
max
distinct
【解决方案1】:
我想你想要:
select p.person_id, max(pe.enc_timestamp) as LastAppt
from patient_encounter pe inner join
person p
on pe.person_id = p.person_id
where pe.enc_timestamp >= '2018-04-05' and
pe.enc_timestamp < '2020-04-06' and
?.billable_ind = 'y' and -- what table is this in ???
p.last_name <> 'ztest'
group by p.person_id
order by p.person_id;
GROUP BY 指定结果集中每一行的定义。这指定您希望每个 person_id 的不同值有一行。
注意事项:
- 修复方法是从
GROUP BY 中删除时间戳。
-
GROUP BY 几乎不需要SELECT DISTINCT。事实上,它很少需要。
- 没有理由在
WHERE 子句中重复重复JOIN 条件。
- 表别名使查询更易于编写和阅读。
- 您应该限定所有列引用。
billing_ind 在哪个表中?
- 您可以简化日期比较。作为一项优势,您可以以天而非毫秒为单位进行思考。