优化这段代码@Select("SELECT SUM(CASE WHEN MONTH(registerTime) =1 THEN 1 ELSE 0 END) 一月, SUM(CASE WHEN MONTH(registerTime) =2 THEN 1 ELSE 0 END) 二月,\n" + "SUM(CASE WHEN MONTH(registerTime) =3 THEN 1 ELSE 0 END) 三月, SUM(CASE WHEN MONTH(registerTime) =4 THEN 1 ELSE 0 END) 四月,\n" + "SUM(CASE WHEN MONTH(registerTime) =5 THEN 1 ELSE 0 END) 五月, SUM(CASE WHEN MONTH(registerTime) =6 THEN 1 ELSE 0 END) 六月,\n" + "SUM(CASE WHEN MONTH(registerTime) =7 THEN 1 ELSE 0 END) 七月, SUM(CASE WHEN MONTH(registerTime) =8 THEN 1 ELSE 0 END) 八月,\n" + "SUM(CASE WHEN MONTH(registerTime) =9 THEN 1 ELSE 0 END) 九月, SUM(CASE WHEN MONTH(registerTime) =10 THEN 1 ELSE 0 END) 十月,\n" + "SUM(CASE WHEN MONTH(registerTime) =11 THEN 1 ELSE 0 END) 十一月, SUM(CASE WHEN MONTH(registerTime) =12 THEN 1 ELSE 0 END) 十二月\n" + "FROM(select DISTINCT contactName,phone,dataRole,typename,regionUid,region,provinceUid,province,address,registerTime\n" + "from (select `user`.uid as customerUid, `user`.contactName, `user`.phone, `user`.dataRole, `user`.typename, `user`.address, \n" + "`user`.registerTime,`user`.provinceUid,`user`.regionUid,`user`.sn, region.region, province.province from region, province, (\n" + "select `user`.*, ma.sn from `user` left join (select * from machine_customer where deleted = 0) ma on `user`.uid = ma.customerUid where \n" + "`user`.deleted = 0) `user` where region.uid=`user`.regionUid and province.uid=`user`.provinceUid) `user`) `user` WHERE registerTime LIKE CONCAT('%',#{year},'%')") Map<String, Integer> selectCustomerByYear(String year);
时间: 2024-01-29 07:03:07 浏览: 143
这段代码的主要问题在于它使用了大量的重复代码,每个月都有一个类似的 SUM(CASE WHEN MONTH(registerTime) =X THEN 1 ELSE 0 END) 的语句。为了优化这段代码,我们可以考虑使用动态 SQL。具体来说,我们可以使用一个 for 循环来生成每个月的语句,然后将它们连接起来。以下是一种可能的实现方式:
```
StringBuilder sqlBuilder = new StringBuilder("SELECT ");
for (int i = 1; i <= 12; i++) {
sqlBuilder.append("SUM(CASE WHEN MONTH(registerTime) = ").append(i).append(" THEN 1 ELSE 0 END) ").append(i).append("月, ");
}
sqlBuilder.deleteCharAt(sqlBuilder.length() - 2); // 去掉最后一个逗号和空格
sqlBuilder.append("FROM (SELECT DISTINCT contactName, phone, dataRole, typename, regionUid, region, provinceUid, province, address, registerTime FROM (SELECT `user`.uid AS customerUid, `user`.contactName, `user`.phone, `user`.dataRole, `user`.typename, `user`.address, `user`.registerTime, `user`.provinceUid, `user`.regionUid, `user`.sn, region.region, province.province FROM region, province, (SELECT `user`.*, ma.sn FROM `user` LEFT JOIN (SELECT * FROM machine_customer WHERE deleted = 0) ma ON `user`.uid = ma.customerUid WHERE `user`.deleted = 0) `user` WHERE region.uid=`user`.regionUid AND province.uid=`user`.provinceUid) `user`) `user` WHERE registerTime LIKE CONCAT('%',#{year},'%')");
```
这样就能够避免重复的代码,并且使代码更加简洁和易于维护。
阅读全文