选择表和表的子集之间的联合中不存在的记录

时间:2018-04-21 21:27:35

标签: sql

我有一张桌子,包括过去,现在和将来的约会。我希望能够运行一个查询,它会给我一个给定日期的约会列表,状态为"没有显示"在表格中没有预约日期。

所以,到目前为止我所拥有的是(pseduocodey)

SELECT *
FROM (SELECT *
    FROM Appointments
    WHERE Appointments.Date >= Today's Date)
WHERE NOT EXISTS
    (SELECT *
    FROM Appointments
    WHERE Appointments.PatID = SUBQUERYRESULTS.PatID)

子查询将是

SELECT *
FROM Appointments
WHERE (Appointments.Status = "NoShow" AND (Appointment.Date is >= Start_date and <= End_date))

我不确定如何包含子查询以使其工作。我是新手,所以请原谅白痴。谢谢。

3 个答案:

答案 0 :(得分:2)

您似乎希望将not exists作为where条件。根据您的描述,这似乎是:

select a.*
from appointments a
where a.status = 'no show' and
      a.date = @date and
      not exists (select 1
                  from appointments a2
                  where a2.patid = a.patid and a2.date > current_ate
                 );

如果日期列有时间组件,则日期比较需要考虑到这一点。

答案 1 :(得分:0)

  

约会......状态为“未显示”,未在表格中预约未来日期

这似乎有效(使用Access 2010测试),并包含“Start_date”和“End_date”比较,以将'NoShow'约会限制为日期范围:

SELECT a1.*
FROM Appointments a1
WHERE a1.Status='NoShow'
    AND a1.Date >= Start_date AND a1.Date <= End_date
    AND NOT EXISTS
    (
        SELECT * 
        FROM Appointments a2 
        WHERE a2.PatID = a1.PatID
            AND a2.Date > a1.Date
    )

答案 2 :(得分:0)

这是另一个选项(虽然未经测试),它使用LEFT JOIN代替子查询:

SELECT t.*
FROM 
    Appointments t LEFT JOIN Appointments u 
    ON t.PatID = u.PatID AND t.Date < u.Date
WHERE
    t.Status = "NoShow"  AND
    t.Date >= Start_date AND 
    t.Date <= End_date   AND
    u.PatID IS NULL

u.PatID IS NULL行基本上会执行这些记录的选择而无需将来约会。