MySQL 在单个查询中获取 COUNT 和 SUM

标签 mysql sql

我使用这个查询:

SELECT 
      `o_p`.`id`, 
      `o`.`user_id` AS `buyer`,
      `product_number` 
FROM `order_products` `o_p` 
LEFT JOIN `order` `o` ON o.id=o_p.id 
WHERE (`o_p`.`product_id`='5') AND (`o`.`pay_status`=1)

然后我得到这个结果:

id buyer product_number

20 7     13

26 7     10

27 19    10

或者你可以在这个 link 看到结果

但我想计算买家的数量,预期为“2”,以及 product_number 的总数,预期为“33”。

我应该如何修复查询。

最佳答案

使用 count(distinct user_id) 作为独立买家的数量,使用 sum(product_number) 作为 product_number 的总数

select count(distinct o.user_id) as buyer_number,
sum(product_number) as product_number_total
from order_products o_p 
left join order o on o.id=o_p.id 
where (o_p.product_id='5') and (o.pay_status=1)

关于MySQL 在单个查询中获取 COUNT 和 SUM,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28955153/

相关文章:

php - 使用 php 中的 session 防止对登录的攻击

python - 使用多个单词搜索(SQLite3)数据库

mysql - 如何在一个查询中同时使用 SELECT 和 UPDATE 语句?

mysql - utf8_general_ci 和 utf8_unicode_ci 有什么区别?

php - 给数据查询

mysql - SQL联盟更新

mysql - 什么时候应该重建数据库索引?

c# - 是否可以在不求助于动态 SQL 的情况下查询用户指定的列名?

sql - 在 BigQuery 中从数组中减去项目

sql - 计算Postgresql中的累计总数