java

关注公众号 jb51net

关闭
首页 > 软件编程 > java > MybatisPlus分组sum求和

MybatisPlus结合groupby实现分组和sum求和的步骤

作者:知识浅谈

这篇文章主要介绍了MybatisPlus结合groupby实现分组和sum求和的步骤,这次使用的是LambdaQueryWrapper,使用QueryWrapper相对来说简单点就不写了,本文分步骤给大家介绍的非常详细,感兴趣的朋友一起看看吧

✅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
  }
]

🍚总结

到此这篇关于MybatisPlus结合groupby实现分组和sum求和的文章就介绍到这了,更多相关MybatisPlus分组sum求和内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

阅读全文