已知数据如下: 7369,SMITH,CLERK,7902,1980-12-17,800,null,20 7499,ALLEN,SALESMAN,7698,1981-02-20,1600,300,30 7521,WARD,SALESMAN,7698,1981-02-22,1250,500,30 7566,JONES,MANAGER,7839,1981-04-02,2975,null,20 7654,MARTIN,SALESMAN,7698,1981-09-28,1250,1400,30 7698,BLAKE,MANAGER,7839,1981-05-01,2850,null,30 7782,CLARK,MANAGER,7839,1981-06-09,2450,null,10 7788,SCOTT,ANALYST,7566,1987-04-19,3000,null,20 7839,KING,PRESIDENT,null,1981-11-17,5000,null,10 7844,TURNER,SALESMAN,7698,1981-09-08,1500,0,30 7876,ADAMS,CLERK,7788,1987-05-23,1100,null,20 7900,JAMES,CLERK,7698,1981-12-03,950,null,30 7902,FORD,ANALYST,7566,1981-12-02,3000,null,20 7934,MILLER,CLERK,7782,1982-01-23,1300,null,10 使用mr程序统计每年入职的人数。 最终结果要求如下: 1. 格式如下: 年份:1980 人数:xxx 年份:1981 人数:xxx ....... 2. 两个分区: 0分区存储 入职年份<1982年的 1分区存储 入职年份>=1982年的 用java语言编写
时间: 2023-07-27 17:11:29 浏览: 96
以下是使用Java语言编写的代码:
```java
import java.sql.*;
public class EmployeeCountByYear {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// 连接数据库
Class.forName("oracle.jdbc.driver.OracleDriver");
conn = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:ORCL", "username", "password");
stmt = conn.createStatement();
// 查询每年入职的人数
String sql = "SELECT SUBSTR(hiredate, 1, 4) AS year, COUNT(*) AS count FROM emp WHERE hiredate < '1982-01-01' GROUP BY SUBSTR(hiredate, 1, 4) UNION SELECT SUBSTR(hiredate, 1, 4) AS year, COUNT(*) AS count FROM emp WHERE hiredate >= '1982-01-01' GROUP BY SUBSTR(hiredate, 1, 4) ORDER BY year";
rs = stmt.executeQuery(sql);
// 打印结果
int year = 0;
while (rs.next()) {
int count = rs.getInt("count");
if (rs.getInt("year") != year) {
System.out.println("年份:" + rs.getInt("year"));
System.out.println("人数:" + count);
year = rs.getInt("year");
} else {
System.out.println("人数:" + count);
}
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// 关闭数据库连接
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
需要注意的是,该代码中的SQL语句是针对Oracle数据库的。如果使用其他数据库,可能需要根据具体情况修改SQL语句。
阅读全文