🍁 作者:知识浅谈,CSDN签约讲师,CSDN博客专家,华为云云享专家,阿里云专家博主
📌 擅长领域:全栈工程师、爬虫、ACM算法
💒 公众号:知识浅谈
🔥网站:vip.zsqt.cc
✅MybatisPlus结合groupby实现分组和sum求和
这次使用的是LambdaQueryWrapper
,使用QueryWrapper
相对来说简单点就不写了
🎈实现GroupBy分组
第一步: 实体类中新增一个字段count
@TableName(value ="user")
@Data
public class User implements Serializable {@TableId(type = IdType.AUTO)private Integer id;@TableField(value = "name")private String name;@TableField(value = "age")private Integer age;@TableField(value = "state")private String state;@TableField(exist = false)private static final long serialVersionUID = 1L;//这个地方@TableField(value = "count(*)",insertStrategy = FieldStrategy.NEVER,updateStrategy = FieldStrategy.NEVER)private Integer count;
}
第二步:查询接口中修改
@GetMapping("/count")public List<User> count(){new QueryWrapper<>()LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();queryWrapper.select(User::getState,User::getCount);queryWrapper.groupBy(User::getState);List<User> list = userService.list(queryWrapper);return list;}
返回的结果
[{"id": null,"name": null,"age": null,"state": "1","count": 3},{"id": null,"name": null,"age": null,"state": "2","count": 2}
]
🎈实现GroupBy分组之后再sum求和
第一步: 实体类中新增一个字段count
@TableName(value ="user")
@Data
public class User implements Serializable {@TableId(type = IdType.AUTO)private Integer id;@TableField(value = "name")private String name;@TableField(value = "age")private Integer age;@TableField(value = "state")private String state;@TableField(exist = false)private static final long serialVersionUID = 1L;@TableField(value = "count(*)",insertStrategy = FieldStrategy.NEVER,updateStrategy = FieldStrategy.NEVER)private Integer count;//这个地方@TableField(value = "sum(age)",insertStrategy = FieldStrategy.NEVER,updateStrategy = FieldStrategy.NEVER)private Integer ages;
}
第二步:查询接口中修改
@GetMapping("/count")public List<User> count(){new QueryWrapper<>()LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();//这个地方新增了一个字段queryWrapper.select(User::getState,User::getCount,User::getAges);queryWrapper.groupBy(User::getState);List<User> list = userService.list(queryWrapper);return list;}
返回的结果
[{"id": null,"name": null,"age": null,"state": "1","count": 3,"ages": 6},{"id": null,"name": null,"age": null,"state": "2","count": 2,"ages": 9}
]
🍚总结
大功告成,撒花致谢🎆🎇🌟,关注我不迷路,带你起飞带你富。
Writted By 知识浅谈