【问题标题】:SQL statement only select items that appear less than twiceSQL 语句只选择出现次数少于两次的项目
【发布时间】:2012-03-23 15:43:50
【问题描述】:

我目前正在开发一个数据库,该数据库存储允许用户在餐厅进行预订的信息。

我正在尝试创建一个 SQL 语句,它返回在预订表中出现少于两次的时间。

目前我有这个,但这只会返回根本没有出现在预订表中的时间。

SELECT *
FROM TIME
WHERE
    TIME NOT IN (
        SELECT reservation.a_time
        FROM 
            RESERVATION
        JOIN TIME ON 
            reservation.a_time = time.time
        WHERE
            reservation.a_date = :the_date
    )
ORDER BY time;

上面的语句返回所有不在reservations 表中的时间。但是,我将如何返回保留表中出现的所有时间,包括出现一次但不出现两次的时间?

谢谢

【问题讨论】:

    标签: sql oracle oracle-sqldeveloper


    【解决方案1】:
    select
      *
    from
      TIME t
    where
      (select 
        count(r.a_time) 
      from 
        RESERVATION r 
      where
        r.a_time = t.time and
        r.a_date = :the_date) < 2
    

    select
      t.time /* and maybe other field, which you need to add to Group By as well */
    from
      TIME t
      left join RESERVATION r on r.a_time = t.time and r.a_date = :the_date
    group by
      t.time
    having
      count(t.time) < 2
    

    我更喜欢第一个,因为它更干净、更清晰并且可以更容易地扩展,尽管有子选择。

    【讨论】:

      【解决方案2】:

      如果您唯一关心的是返回只出现一次的reservation.a_times,那么就可以了:

      SELECT reservation.a_time
      FROM RESERVATION
      GROUP BY reservation.a_time
      HAVING COUNT(*) = 1;
      

      这将按时间对所有 RESERVATION 条目进行分组,并且只返回只有一个成员的组。

      【讨论】:

      • 这不会返回完全没有保留的时间。
      • @GolezTrol 然后他的问题措辞奇怪,因为他特意要求all times which appear in the reservations table
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-12
      • 2014-04-02
      • 1970-01-01
      相关资源
      最近更新 更多