Java开发中,先根据离职时间利用sql查出在起始年月到结束年月区间的离职人员,并且省份包含上海、广州、深圳。如何利用lambda表示再查询出每个省份每个月离职率
时间: 2023-05-26 08:02:21 浏览: 133
假设有一张名为employee的表,其中有以下字段:id, name, province, leave_date。
先根据离职时间查出在起始年月到结束年月区间的离职人员:
```
SELECT * FROM employee WHERE leave_date BETWEEN '起始年月' AND '结束年月'
```
筛选出省份包含上海、广州、深圳的离职员工:
```
SELECT * FROM employee WHERE leave_date BETWEEN '起始年月' AND '结束年月' AND province IN ('上海', '广州', '深圳')
```
利用lambda表达式查询出每个省份每个月的离职率:
```java
List<Employee> employees = ...; // 假设为查询结果集
// 以省份和月份为键,统计离职次数
Map<String, Map<String, Integer>> leaveCounts = employees.stream()
.collect(Collectors.groupingBy(Employee::getProvince,
Collectors.groupingBy(emp -> emp.getLeaveDate().substring(0, 7), Collectors.summingInt(emp -> 1))));
// 以省份和月份为键,统计总人数
Map<String, Map<String, Integer>> totalCounts = employees.stream()
.collect(Collectors.groupingBy(Employee::getProvince,
Collectors.groupingBy(emp -> emp.getLeaveDate().substring(0, 7), Collectors.summingInt(emp -> 1))));
// 计算每个省份每个月的离职率
Map<String, Map<String, Double>> leaveRates = new HashMap<>();
for (String province : leaveCounts.keySet()) {
Map<String, Integer> provinceLeaveCounts = leaveCounts.get(province);
Map<String, Integer> provinceTotalCounts = totalCounts.get(province);
for (String month : provinceTotalCounts.keySet()) {
double rate = provinceLeaveCounts.getOrDefault(month, 0) / (double) provinceTotalCounts.get(month);
leaveRates.computeIfAbsent(province, k -> new HashMap<>()).put(month, rate);
}
}
```
其中Employee类的定义为:
```java
public class Employee {
private int id;
private String name;
private String province;
private String leaveDate;
// 省略构造方法、getter和setter
}
```
阅读全文