如何获取具有受影响行数的列的SUM
我正在尝试获取列的总和,我还想返回受影响列的数量。
示例:
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
现在我想要为特定客户(customer_id)汇总金额列,并返回项目数(计算受影响的行数)
我这样做但它只得到金额的总和,我还希望从这个单一查询中获得受影响的行数(计数):
SELECT SUM(amount) AS amount
FROM orders
WHERE customer_id = 2
答案 0 :(得分:5)
也可以COUNT
:
SELECT SUM(amount) AS amount, COUNT(*) AS cnt
FROM orders
WHERE customer_id = 2
如果amount
是可以为空的字段,并且您只想计算NOT NULL
行,请执行COUNT(amount)
而不是COUNT(*)
。
答案 1 :(得分:0)
SELECT SUM(amount) AS amount, COUNT(1) AS cnt
FROM orders
WHERE customer_id = 2