HAVING子句使您可以指定条件,以过滤出哪些组输出出现在输出中。
WHERE子句将条件放置在所选列上,而HAVING子句将条件放置在GROUP BY子句创建的组上。
Having - 语法
以下是HAVING子句的语法-
ij> SELECT column1, column2 . . . from table_name GROUP BY column having condition;
Having - 命令行示例
假设无涯教程在数据库中有一个名为Employees的表,其中包含13条记录,如下所示-
ID |NAME |SALARY |LOCATION ------------------------------------------------------------------ 1 |Amit |30000 |Hyderabad 2 |Rahul |39000 |Lucknow 3 |Kalyan |40000 |Vishakhapatnam 4 |Renuka |50000 |Hyderabad 5 |Learnfk |15000 |Vishakhapatnam 6 |Krishna |40000 |Hyderabad 7 |Trupthi |45000 |Vishakhapatnam 8 |Raghav |12000 |Lucknow 9 |Radha |50000 |Delhi 10 |Anirudh |15000 |Mumbai 11 |Tara |45000 |Kochin 12 |Sucharita |44000 |Kochin 13 |Rizwan |20000 |Lucknow
以下查询显示该位置至少有3名员工的员工的最高薪水-
ij> SELECT Location, MAX(Salary) from Employees GROUP BY Location having count(Location)>=3;
这将产生以下输出-
LOCATION |2 ------------------------------------------------------------ Hyderabad |50000 Lucknow |39000 Vishakhapatnam |45000 3 rows selected
Having - JDBC示例
以下JDBC示例演示了如何使用Group By子句以及如何使用JDBC程序在Apache Derby中的表上执行CURD操作,在这里,无涯教程使用嵌入式驱动程序连接到名为sampleDB的数据库(如果不存在则创建)。
import java.sql.Connection; import java.sql.DriverManager; import java.sql.Statement; import java.sql.ResultSet; public class HavingClauseExample { public static void main(String args[]) throws Exception { //注册驱动 Class.forName("org.apache.derby.jdbc.EmbeddedDriver"); //创建连接 String URL="jdbc:derby:sampleDB;create=true"; Connection conn=DriverManager.getConnection(URL); //获取Statement对象 Statement stmt=conn.createStatement(); //创建表结构,插入一些测试数据 stmt.execute("CREATE TABLE EmployeesData( " + "Id INT NOT NULL GENERATED ALWAYS AS IDENTITY, " + "Name VARCHAR(255), " + "Salary INT NOT NULL, " + "Location VARCHAR(255), " + "PRIMARY KEY (Id))"); stmt.execute("INSERT INTO EmployeesData(Name, Salary, Location) " + "VALUES ('Amit', 30000, 'Hyderabad'), " + "('Rahul', 39000, 'Lucknow'), " + "('Renuka', 50000, 'Hyderabad'), " + "('Learnfk', 15000, 'Vishakhapatnam'), " + "('Kalyan', 40000, 'Hyderabad'), " + "('Trupthi', 45000, 'Vishakhapatnam'), " + "('Raghav', 12000, 'Lucknow'), " + "('Suchatra', 33000, 'Vishakhapatnam'), " + "('Rizwan', 20000, 'Lucknow')"); //执行SQL语句 String query="SELECT Location, MAX(Salary) " + "from EmployeesData GROUP BY Location having " + "count(Location)>=3"; ResultSet rs=stmt.executeQuery(query); while(rs.next()) { System.out.println(rs.getString(1)); System.out.println(rs.getString(2)); System.out.println(" "); } } }
在执行上述程序时,您将获得以下输出-
Hyderabad 50000 Lucknow 39000 Vishakhapatnam 45000
参考链接
https://www.learnfk.com/derby/apache-derby-having-clause.html
标签:Vishakhapatnam,Hyderabad,Lucknow,子句,无涯,50000,Location,Derby,Having From: https://blog.51cto.com/u_14033984/7799240