SQL - Having 子句

  • 简述

    HAVING Clause使您能够指定过滤哪些组结果出现在结果中的条件。
    WHERE 子句将条件放在选定的列上,而 HAVING 子句将条件放在由 GROUP BY 子句创建的组上。
  • 句法

    以下代码块显示了 HAVING 子句在查询中的位置。
    
    SELECT
    FROM
    WHERE
    GROUP BY
    HAVING
    ORDER BY
    
    HAVING 子句必须在查询中的 GROUP BY 子句之后,并且如果使用,还必须在 ORDER BY 子句之前。以下代码块具有 SELECT 语句的语法,包括 HAVING 子句 -
    
    SELECT column1, column2
    FROM table1, table2
    WHERE [ conditions ]
    GROUP BY column1, column2
    HAVING [ conditions ]
    ORDER BY column1, column2
    
  • 例子

    考虑具有以下记录的 CUSTOMERS 表。
    
    +----+----------+-----+-----------+----------+
    | ID | NAME     | AGE | ADDRESS   | SALARY   |
    +----+----------+-----+-----------+----------+
    |  1 | Ramesh   |  32 | Ahmedabad |  2000.00 |
    |  2 | Khilan   |  25 | Delhi     |  1500.00 |
    |  3 | kaushik  |  23 | Kota      |  2000.00 |
    |  4 | Chaitali |  25 | Mumbai    |  6500.00 |
    |  5 | Hardik   |  27 | Bhopal    |  8500.00 |
    |  6 | Komal    |  22 | MP        |  4500.00 |
    |  7 | Muffy    |  24 | Indore    | 10000.00 |
    +----+----------+-----+-----------+----------+
    
    以下是一个示例,它将显示大于或等于 2 的相似年龄计数的记录。
    
    SQL > SELECT ID, NAME, AGE, ADDRESS, SALARY
    FROM CUSTOMERS
    GROUP BY age
    HAVING COUNT(age) >= 2;
    
    这将产生以下结果 -
    +----+--------+-----+---------+---------+
    | ID | NAME   | AGE | ADDRESS | SALARY  |
    +----+--------+-----+---------+---------+
    |  2 | Khilan |  25 | Delhi   | 1500.00 |
    +----+--------+-----+---------+---------+