首页 > 解决方案 > 对于 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 

标签: mysqlsqloraclegroup-bysum

解决方案


这是一个简单的聚合查询。

假设表被调用books并且它的列被命名为name,idno_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

推荐阅读