代码之家  ›  专栏  ›  技术社区  ›  Georgi Michev

仅对一列使用WHERE子句

  •  0
  • Georgi Michev  · 技术社区  · 5 年前

    我有个问题

    SELECT COUNT(dog.id) as dogs_count, SUM(dog.age) AS total_age WHERE dog.owner IS NULL; 
    

    我有两只狗,每只都两岁了。其中一只狗没有主人。 查询应该返回1表示狗的数量(因为只有一个没有主人),返回4表示狗的总年龄,因为狗的年龄总和是4

    2 回复  |  直到 5 年前
        1
  •  1
  •   Gordon Linoff    5 年前

    如果你愿意 流浪者和宠物分开,然后可以使用聚合:

    SELECT (CASE WHEN d.owner IS NULL THEN 'stray' ELSE 'pet' END) as status,
           COUNT(*) as dogs_count, SUM(d.age) AS total_age
    FROM dogs d
    WHERE d.owner IS NULL
    GROUP BY status;
    

    还可以使用条件聚合将所有值放在一行中:

    SELECT COUNT(*) as dogs_count, SUM(d.age) AS total_age,
           SUM(d.owner IS NULL) as num_strays,
           SUM(CASE WHEN d.owner IS NULL THEN d.age ELSE 0 END) as strays_age
    FROM dogs d
    
        2
  •  0
  •   Yogesh Sharma    5 年前

    select count(*) as Total_Dogs, sum(d.owner IS NOT NULL) as dogs_count, 
           sum(d.age) as total_age
    from dog d;