簡體   English   中英

SQL查詢以在一個表中查找重復項,但前提是至少有一個重復項具有位於不同表中的約會

[英]SQL Query to find duplicates in one table but only if at least one of the duplicates has an appointment which is in a different table

感謝這個偉大的社區,我在數據搜索方面已經取得了巨大的成功。 使用:

select patient.last, patient.first, patient.birth, count(*)
from patient
group by patient.last, patient.first, patient.birth
having count(*) > 1

它列出了我所有的重復值! 現在,我想更進一步,以便我可以只列出那些在某一天有約會的重復項。 不過,我遇到了幾個問題。

首先只有兩個副本中的一個會有約會。
其次,約會日期存儲在不同的表上(很有趣,稱為 APPT)

我試過:

select appt.date
from appt
where appt.date=curdate()+1
union
select patient.last, patient.first, patient.birth, count(*)
from patient
group by patient.last, patient.first, patient.birth
having count(*) > 1

但這導致了列不匹配的錯誤。 我不知道如何進行內連接,因為當我選擇 appt.date 時,它​​會影響組。

有什么想法嗎?

您可以使用exists

select p.last, p.first, p.birth, count(*)
from patient p
where exists (select 1
              from appt a
              where a.date = curdate() and
                    a.patunique = p.patunique
             )
group by p.last, p.first, p.birth
having count(*) > 1;

注意:您需要一種方法來識別每次預約的患者。 這假設有一列,如提供鏈接的patunique

我假設(如你的評論說)有一列patunique表中的patient是主鍵,也是表appt其refernces在表中的列patient
所以使用 EXISTS 兩次來識別滿足條件的行:

select p.last, p.first, p.birth, count(*) counter
from patient p
where 
  exists (select 1 from patient where patunique <> p.patunique and last = p.last and first = p.first and birth = p.birth)
  and 
  exists (select 1 from appt where patunique = p.patunique and date = curdate() + 1)
group by p.last, p.first, p.birth

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM