当COUNT值等于零时,SQL失败/不生成

时间:2016-11-04 06:48:09

标签: sql ms-access

我正在尝试为人们生成一个列表,查看可用的&取消了类,不知怎的,我的SQL只打印了那个保留的人,班级的人从不保留它从未显示过。

我怀疑是因为 HAVING 导致只生成保留类。

我的表:

CID, ClassLevel, 开始日期, 开始时间, 持续时间, Descp, 状态, TID

enter image description here ClassReservation

预定ID, 中, CID, 状态

enter image description here

当生成只显示人们保留的类时,但是创建了人们没有保留的类将不会出现。

enter image description here

SELECT Classes.CID
    ,'Date: ' & Classes.StartDate & ', Start Time: ' & Classes.StartTime & ', Duration: ' & Classes.Duration & ', Description: ' & Classes.Descp & ', Status:  ' & Classes.STATUS AS CCOM
FROM Classes
INNER JOIN ClassesReservation ON Classes.CID = ClassesReservation.CID
WHERE (
        Classes.STATUS = 'active'
        OR Classes.STATUS = 'cancelled'
        )
    AND Classes.StartDATE > NOW
GROUP BY Classes.CID
    ,Classes.StartDate
    ,Classes.StartTime
    ,Classes.Duration
    ,Classes.Descp
    ,Classes.STATUS
HAVING COUNT(ClassesReservation.CID) < 20
    OR COUNT(ClassesReservation.CID) > 0

1 个答案:

答案 0 :(得分:0)

我会写这样的查询:

SELECT c.CID,
       ('Date: ' & c.StartDate & ', Start Time: ' & c.StartTime & ', Duration: ' & Classes.Duration & ', Description: ' & c.Descp & ', Status:  ' & c.STATUS
       ) AS CCOM
FROM Classes as c INNER JOIN
     (SELECT cr.CID, COUNT(*) as NumReserved
      FROM ClassesReservation as cr
      GROUP BY cr.CID
     ) cr
     ON c.CID = cr.CID
WHERE c.STATUS IN ('active', 'cancelled') AND
      c.StartDATE > NOW
HAVING cr.NumReserved > 0 AND cr.NumReserved < 20;

注意:

  • 表别名使查询更易于编写和阅读。
  • IN比通过=连接的一堆OR条款更具可读性。
  • 将聚合移动到子查询中简化了查询。
  • 您的真正问题可能只是OR子句中的HAVING