当前位置:   article > 正文

MySQL查询之sum() + group by查询sum()中增加条件_mysql group by sum

mysql group by sum
  1. <select id="queryPage" resultType="">
  2. SELECT picc_user.*,
  3. sys_dept.`name` AS deptName,
  4. sum(IF(picc_score.score_expire_time > NOW(), picc_score.score_not_used, 0)) AS scoreNotUsed,
  5. sum(picc_score.score_number) AS scoreCount
  6. FROM picc_score
  7. LEFT JOIN picc_user ON picc_user.id = picc_score.picc_user_id
  8. LEFT JOIN sys_dept ON picc_score.dept_id = sys_dept.dept_id
  9. <where>
  10. <if test="deptId != null">
  11. picc_score.dept_id = #{deptId}
  12. </if>
  13. <if test="piccUserId != null">
  14. AND picc_score.picc_user_id = #{piccUserId}
  15. </if>
  16. <if test="phone!= null and phone!= ''">
  17. <bind name="phone" value="'%' + phone + '%'"/>
  18. AND picc_score.phone like #{phone}
  19. </if>
  20. </where>
  21. GROUP BY picc_score.dept_id, picc_score.picc_user_id, sys_dept.`name`
  22. </select>
  23. <select id="getInfo" resultType="">
  24. SELECT picc_user.*,
  25. sys_dept.`name` AS deptName,
  26. IFNULL((SELECT SUM(score_not_used)
  27. FROM picc_score
  28. WHERE dept_id = #{deptId}
  29. AND picc_user_id = #{userId}
  30. AND score_expire_time > NOW()), 0) AS scoreNotUsed,
  31. sum(picc_score.score_number) AS scoreCount
  32. FROM picc_score
  33. LEFT JOIN picc_user ON picc_user.id = picc_score.picc_user_id
  34. LEFT JOIN sys_dept ON picc_score.dept_id = sys_dept.dept_id
  35. where picc_score.dept_id = #{deptId}
  36. and picc_score.picc_user_id = #{userId}
  37. GROUP BY picc_score.dept_id, picc_score.picc_user_id, sys_dept.`name`
  38. </select>

以上两种查询方法,第一个是分页列表,第二个是单条数据详情(可以优化使用第一种的if条件)

sum(IF('条件判断''求和的字段''NULL不计算'))  as  '别名'

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/喵喵爱编程/article/detail/986657
推荐阅读
相关标签
  

闽ICP备14008679号