代码之家  ›  专栏  ›  技术社区  ›  DilTeam

比较SQL中的聚合值

  •  3
  • DilTeam  · 技术社区  · 6 年前

    假设我有三张这样的桌子:

    create table garage (id INT);
    create table floor (id INT, garage_id INT);
    create table parking_spot (id INT, floor_id INT, is_occupied INT);
    

    我想打印这个问题的答案:车库满了吗?换句话说,所有的地方都被占领了吗?

    我知道我可以分别运行以下两个查询。

    下面的查询给出了车库的总位置:

    select count(*) from parking_spot ps
      join floor f on ps.floor_id = f.id
      join garage g on f.garage_id = g.id
      where g.id = 2
    

    下面是车库占用的位置:

    select count(*) from parking_spot ps
      join floor f on ps.floor_id = f.id
      join garage g on f.garage_id = g.id
      where g.id = 2 and ps.is_occupied = 1;
    

    但我想写一篇 单身 查询以比较这两个SQLs&打印“车库已满”或“车库未满”。我该怎么做?

    3 回复  |  直到 6 年前
        1
  •  2
  •   krokodilko    6 年前

    您不需要计算所有记录,只需检查是否至少有一个或没有空闲空间:

    SELECT CASE WHEN EXISTS (
          select * from parking_spot ps
          join floor f on ps.floor_id = f.id
          join garage g on f.garage_id = g.id
          where g.id = 2 and ( ps.is_occupied <> 1 OR ps.is_occupied IS NULL )
        ) 
      THEN 'Garage is not full' ELSE 'Garage is full'
    END;
    
        2
  •  1
  •   juergen d    6 年前
    select sum(ps.is_occupied = 0) = 0 as is_full
    from parking_spot ps
    join floor f on ps.floor_id = f.id
    where f.garage_id = 2
    

    这个 sum() 提供空闲插槽的数量。如果是的话 0 然后车库就满了。

        3
  •  0
  •   DilTeam    6 年前

    我喜欢@juergen-d在上面给出的答案,但为了完整起见,根据我的要求修改了他的答案:

    select
      case when sum(ps.is_occupied = 0) = 0 then 'Garage is full'
           else 'Garage is NOT full'
      end
      from parking_spot ps
        join floor f on ps.floor_id = f.id
        where f.garage_id = 2;
    

    经过进一步的审查,似乎“存在时”表现更好,因为不需要计算,所以我接受了@krokodilko给出的答案。这里是:

    SELECT CASE WHEN EXISTS (
          select * from parking_spot ps
          join floor f on ps.floor_id = f.id
          where f.garage_id = 1 and ( ps.is_occupied <> 1 OR ps.is_occupied IS NULL )
        ) 
      THEN 'Garage is not full' ELSE 'Garage is full'
    END;