mysql - 对于 sql 中的特定条件,如何计算同一列中的数据总和?
问题描述
book1_part1 1 00000118323
book1_part1 1 00000118323
book1_part1 1 00000118323
book1_part1 1 00000118323
book1_part1 2 00000118323
book1_part1 1 00000118337
book1_part1 1 00000118337
book1_part1 1 00000118337
book1_part1 1 00000118337
book1_part1 1 00000118337
book1_part1 1 00000118337
book1_part1 2 00000118337
book1_part1 1 00000118337
book1_part1 1 00000118343
每本书都有 id 并且这个 id 有副本数,所以数据库看起来像上面那样,结果应该是:
book1_part1 00000118323 have 6 copies
book1_part1 00000118337 have 8 copies
book1_part1 00000118343 have 1 copy
解决方案
这是一个简单的聚合查询。
假设表被调用books
并且它的列被命名为name
,id
和no_copies
,你会去:
select name, id, sum(no_copies) total_no_copies
from books
group by name, id
您可以使用字符串连接轻松生成预期的短语 - 尽管此任务更适合您的应用程序:
select
name,
concat(
id,
' has ',
sum(no_copies),
case when sum(no_copies) = 1 then ' copy' else ' copies' end
) info
from books
group by name, id
推荐阅读
- graphql - 类型应该使用 Apollo Graphql 引用特定的枚举或联合
- javascript - 当且仅当有 2 行或更多行要显示时,如何缩进第一行?
- windows - 如何让背景图像显示在 Windows Mail 10 应用程序中?
- python - while 循环不会对齐并继续代码并继续循环
- python - 简单邮件传输协议脚本错误
- r - 使用数据字典应用值替换
- c# - 从字典中获取前 n 个值的最佳方法是什么?
- c++ - 如何将值插入向量数组
- gradle - Gradle 在启用并行构建的情况下构建模块的顺序是什么?
- swift - 如何防止 SceneKit 动画在加载时立即播放?