[英]How can be sum number of data in the same column for specific condition in 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
,您將 go:
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.