简体   繁体   English

MySQL 4 SUM如果两行在给定列上具有相同的值

[英]MySQL 4 SUM if two rows have the same value on a given column

I'm using an (OLD) MySQL 4.0 database and I need to sum quantities when for two rows, a specific column has the same value. 我使用的是(旧)MySQL 4.0数据库,当两行的特定列具有相同的值时,我需要对数量求和。

Example, 例,

So let,s say I have these columns: doc_nr | 因此,假设我有这些列:doc_nr | client_name | client_name | article_id | article_id | qty 数量

When they are inserted into the database, they are separated into different rows each with quantity 1 (complicated amount of services control background for upper management) 将它们插入数据库后,它们被分成不同的行,每个行的数量为1(复杂的服务数量控制着上层管理的背景)

What I want to do is that, for the same article_id, and for the same doc_nr (which imply that it's for the same customer) if the article_id is the same, I want to output the quantity as a SUM of them. 我想做的是,对于相同的article_id和相同的doc_nr(这意味着它是针对同一位客户),如果article_id相同,我想将数量作为它们的总和输出。

So, for a customer which ordered a quantity of 2 articles, that is then inserted as two separate rows with quantity 1, how do I output quantity 2 again? 因此,对于订购了2件商品的客户,然后将其插入数量为1的两行中,如何再次输出数量2?

You could use a GROUP BY query: 您可以使用GROUP BY查询:

SELECT doc_nr, client_name, article_id, SUM(qty) AS qty
FROM yourtable
GROUP BY doc_nr, client_name, article_id

if qty is always 1, instead of SUM(qty) you could just use COUNT(*) that counts the number of grouped rows. 如果qty始终为1,而不是SUM(qty) ,则可以使用COUNT(*)来计算分组行的数量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM