简体   繁体   中英

How to get SUM of a column with number of affected rows

How to get SUM of a column with number of affected rows

I am trying to get the sum of a column and I will also like to return the number of affected columns.

Example:

orders table

id    customer_id       name      amount
----------------------------------------
1      2                burger    5.00
2      2                pizza     6.00
3      2                grape     1.00
4      1                sandwich  4.00

Now I want to SUM the amount column for a particular customer(customer_id) and also return number of items(count rows affected)

I am doing this but it only gets the sum of the amount, I would also like to get number number affected rows (count) from this single query:

SELECT SUM(amount) AS amount
FROM orders
WHERE customer_id = 2

Just do a COUNT as well:

SELECT SUM(amount) AS amount, COUNT(*) AS cnt
FROM orders
WHERE customer_id = 2

If amount is a nullable field and you want to only count NOT NULL rows, then do a COUNT(amount) instead of COUNT(*) .

SELECT SUM(amount) AS amount, COUNT(1) AS cnt
FROM orders
WHERE customer_id = 2

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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