Apache Derby 简明教程

Apache Derby - GROUP BY Clause

GROUP BY 子句与 SELECT 语句一起使用。它用于在数据相同的情况下形成子集。通常,此子句后面跟着 ORDER BY 子句,并置于 WHERE 子句之后。

The GROUP BY clause is used with SELECT statements. It is used to form subsets in case of identical data. Usually, this clause is followed by ORDER BY clause and placed after the WHERE clause.

Syntax

以下是 GROUP BY 子句的语法:

Following is the syntax of GROUP BY clause −

ij>SELECT column1, column2, . . . table_name GROUP BY column1, column2, . . .;

Example

假设我们在数据库中有一个名为 Employees 的表,其中包含以下记录 −

Suppose we have a table named Employees in the database with the following records −

ID |NAME    |SALARY |LOCATION
------------------------------------------------------------------
1  |Amit    |30000  |Hyderabad
2  |Rahul   |39000  |Lucknow
3  |Renuka  |50000  |Hyderabad
4  |Archana |15000  |Vishakhapatnam
5  |Kalyan  |40000  |Hyderabad
6  |Trupthi |45000  |Vishakhapatnam
7  |Raghav  |12000  |Lucknow
8  |Suchatra|33000  |Vishakhapatnam
9  |Rizwan  |20000  |Lucknow

带 GROUP BY 子句的以下 SELECT 语句基于位置对表分组。它显示给定位置员工获得的总薪水金额。

The following SELECT statement with GROUP BY clause groups the table based on location. It displays the total amount of salary given to employees at a location.

ij> SELECT Location, SUM(Salary) from Employees GROUP BY Location;

这会产生以下输出 −

This will generate the following output −

LOCATION        |2
-------------------------------------------------------
Hyderabad       |120000
Lucknow         |71000
Vishakhapatnam  |93000
3 rows selected

同样,以下查询找到用于为某个位置的员工支付的平均薪水金额。

In the same way, following query finds the average amount spent on the employees as salary in a location.

ij> SELECT Location, AVG(Salary) from Employees GROUP BY Location;

这会产生以下输出 −

This will generate the following output −

LOCATION        |2
-----------------------------------------------------
Hyderabad       |40000
Lucknow         |23666
Vishakhapatnam  |31000
3 rows selected

Group By clause JDBC example

本节将教您如何在 JDBC 应用程序中使用 Group By 子句并在 Apache Derby 数据库中的表上执行 CURD 操作。

This section teaches you how to use Group By clause and perform CURD operations on a table in Apache Derby database using JDBC application.

如果你想使用网络客户端访问 Derby 网络服务器,请确保服务器正在运行。网络客户端驱动程序的类名为 org.apache.derby.jdbc.ClientDriver,URL 为 jdbc:derby://localhost:1527/ DATABASE_NAME;*create=true;user=*USER_NAME;*password=*PASSWORD "

If you want to request the Derby network server using network client, make sure that the server is up and running. The class name for the Network client driver is org.apache.derby.jdbc.ClientDriver and the URL is jdbc:derby://localhost:1527/DATABASE_NAME;*create=true;user=*USER_NAME;*password=*PASSWORD"

按照以下步骤使用 Group By 子句并在 Apache Derby 中对表执行 CURD 操作:

Follow the steps given below to use Group By clause and perform CURD operations on a table in Apache Derby

Step 1: Register the driver

要与数据库通信,首先需要注册驱动程序。类 ClassforName() 方法接受表示类名称的 String 值,将其加载到内存中,这会自动注册它。使用此方法注册驱动程序。

To communicate with the database, first of all, you need to register the driver. The forName() method of the class Class accepts a String value representing a class name loads it in to the memory, which automatically registers it. Register the driver using this method.

Step 2: Get the connection

通常,我们与数据库进行通信时执行的第一步就是与数据库连接。类 Connection 表示与数据库服务器之间的物理连接。你可以通过调用类 DriverManager 的方法 getConnection() 创建连接对象。使用此方法来创建连接。

In general, the first step we do to communicate to the database is to connect with it. The Connection class represents the physical connection with a database server. You can create a connection object by invoking the getConnection() method of the DriverManager class. Create a connection using this method.

Step 3: Create a statement object

您需要创建一个 StatementPreparedStatementCallableStatement 对象才能向数据库发送 SQL 语句。您可以分别使用 createStatement(), prepareStatement() and, prepareCall() 方法创建这些对象。使用相应的方法创建其中一个对象。

You need to create a Statement or PreparedStatement or, CallableStatement objects to send SQL statements to the database. You can create these using the methods createStatement(), prepareStatement() and, prepareCall() respectively. Create either of these objects using the appropriate method.

Step 4: Execute the query

创建语句之后,你需要执行语句。 Statement 类提供多种方法来执行查询,例如 execute() 方法,用于执行返回多个结果集的语句。 executeUpdate() 方法用于执行诸如 INSERT、UPDATE、DELETE 这类查询。 executeQuery() 方法返回数据。使用其中一种方法并执行之前创建的语句。

After creating a statement, you need to execute it. The Statement class provides various methods to execute a query like the execute() method to execute a statement that returns more than one result set. The executeUpdate() method is used to execute queries like INSERT, UPDATE, DELETE. The executeQuery() method returns data. Use either of these methods and execute the statement created previously.

Example

以下 JDBC 示例演示如何使用 Group By 子句并使用 JDBC 程序对 Apache Derby 中的表执行 CURD 操作。此处,我们使用嵌入式驱动程序连接到一个名为 sampleDB 的数据库(如果不存在,则创建该数据库)。

Following JDBC example demonstrates how to use Group By clause and perform CURD operations on a table in Apache Derby using JDBC program. Here, we are connecting to a database named sampleDB (will create if it does not exist) using the embedded driver.

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.ResultSet;
public class GroupByClauseExample {
   public static void main(String args[]) throws Exception {
      //Registering the driver
      Class.forName("org.apache.derby.jdbc.EmbeddedDriver");

      //Getting the Connection object
      String URL = "jdbc:derby:sampleDB;create=true";
      Connection conn = DriverManager.getConnection(URL);

      //Creating the Statement object
      Statement stmt = conn.createStatement();

      //Creating a table and populating it
      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'), "
         + "('Archana', 15000, 'Vishakhapatnam'), "
         + "('Kalyan', 40000, 'Hyderabad'), "
         + "('Trupthi', 45000, 'Vishakhapatnam'), "
         + "('Raghav', 12000, 'Lucknow'), "
         + "('Suchatra', 33000, 'Vishakhapatnam'), "
         + "('Rizwan', 20000, 'Lucknow')");

      //Executing the query
      String query = "SELECT Location, SUM(Salary) from EmployeesData GROUP BY Location";
      ResultSet rs = stmt.executeQuery(query);
      while(rs.next()) {
         System.out.println("Location: "+rs.getString(1));
         System.out.println("Sum of salary: "+rs.getString(2));
         System.out.println(" ");
      }
   }
}

Output

执行上述程序时,你将得到以下输出:

On executing the above program, you will get the following output −

Location: Hyderabad
Sum of salary: 120000

Location: Lucknow
Sum of salary: 71000

Location: Vishakhapatnam
Sum of salary: 93000