Sum列总数(每个重复行数据只有一次)

时间:2015-06-02 11:37:14

标签: mysql sql

假设我有以下orders表,并且我正在检索所有failed个订单。

+----+------------------+-------+--------+
| id | email            | total | status |
+----+------------------+-------+--------+
| 1  | john@example.com | 39.99 | failed |
|----|------------------|-------|--------+
| 2  | john@example.com | 39.99 | failed |
|----|------------------|-------|--------+
| 3  | pete@example.com | 19.99 | failed |
+----+------------------+-------+--------+

我需要获取失败订单的总数以及它们的总计,但每个重复行只需要一次(当emailtotal相同时,行被认为是重复的)

目前我有一个非常简单的查询,可以获得所有failed订单的总数。我不确定如何修改它以返回所需的数据(我已尝试弄乱DISTINCTGROUP BY无效。)

SELECT COUNT(*) AS `count`, SUM(`total`) AS `grand_total` FROM `orders` WHERE `status` = 'failed';

返回:

+-------+-------------+
| count | grand_total |
+-------+-------------+
|   3   |   99.97     |
+-------+-------------+

我想要返回的结果是:

+-------+-------------+
| count | grand_total |
+-------+-------------+
|   2   |    59.98    |
+-------+-------------+

(结果将省略第二行,因为emailtotal具有与第一行中相同的值)

是否可以在单个查询中检索此数据?

2 个答案:

答案 0 :(得分:4)

我认为您需要在子查询中执行distinctgroup by

select count(*), sum(total)
from (select distinct email, total
      from orders
      where status = 'failed'
     ) et;

答案 1 :(得分:0)

也许吧:

SELECT COUNT(DISTINCT email, total)
FROM orders WHERE status = 'failed'
;

在这种情况下,我们从电子邮件和总计中构建伪唯一密钥,并仅计算唯一出现次数... 它应该工作......