sql使用GROUP_CONCAT实现分组过后的数据拼接去重操作
需求如下:按照ansuid字段分组,分组过后判断error_msg是否重复,重复的话error_msg就只保留一个,没有重复就进行拼接
//方法一:sql实现: select a.id,a.ansuid,a.relation_error_ansuid,GROUP_CONCAT( distinct a.error_msg) as error_msg,a.deleteflg,a.add_time,a.relation_error_pic_url from ( select a.id,a.ansuid,a.relation_error_ansuid,a.error_msg,a.deleteflg,a.add_time,a.relation_error_pic_url from t_wjdc_answer_exception a where a.deleteflg=0) a GROUP BY a.ansuid HAVING a.ansuid in (02b00813bdf74b0c9e0c,d7f5f66ff4da43098969) 实际开发时in后面可替换以下: <foreach collection="list" index="index" item="item" open="(" separator="," close=")"> #{ item} </foreach>
获得如下效果:
方法二:代码实现 //sql就不需要上面那种写法,直接就单表sql查出所有的,然后程序处理,不过这种的是通过单个id把一条重复的全部查出来,只针对单个的,也可以在前端在进行额外处理,推荐使用sql List<Map<String, Object>> exceptionList = questionnaireService.getExceptionByAnsuid(id); //拼接 StringBuffer exceptionReason = new StringBuffer(); int num = 0; for (Map<String, Object> objectMap : exceptionList) { //重点就是这里的contains处理,contains:判断字符串是否包含,列如已经存在字符串abc,使用contains判断是否包含ab,如果包含返回true if (!exceptionReason.toString().contains(objectMap.get("error_msg").toString())) { num += 1; if (num == 1) { exceptionReason.append("!小票识别异常,异常原因:").append(num+"、"+objectMap.get("error_msg")); } else { exceptionReason.append("。").append(num+"、"+objectMap.get("error_msg")); } } } model.addAttribute("exceptionReason",exceptionReason.toString());