按结果分组的MySQL组

时间:2017-03-01 12:20:59

标签: mysql

我有一个非常简单的表,其中包含以下列:

id | customer_id | total | created_at

我正在运行此查询以获取过去十天每天的结果:

SELECT SUM(total) AS total, DATE_FORMAT(created_at, "%d/%m/%Y") AS date
FROM table
WHERE created_at BETWEEN "2017-02-20" AND "2017-03-01"
GROUP BY created_at
ORDER BY created_at DESC

这很好用,但我刚刚注意到导入的行由于某种原因而被复制的问题所以我想更新查询以便能够处理这种情况,如果它再次发生,换句话说当日期和客户ID相同时(总数也相同),选择一行而不是全部。

如果我将customer_id添加到该组似乎可以正常工作,但问题就在于,当我只想要总体总数时,查询会返回每个客户每天的结果。

我已经尝试了一些东西,但我还没有破解它,我认为使用子查询和/或内连接可以实现,到目前为止我已经尝试了这个但是数字非常错误:

SELECT
    created_at,
    (
        SELECT SUM(total)
        FROM table test
        WHERE test.created_at = table.created_at
        AND test.customer_id = table.customer_id
        GROUP BY customer_id, created_at
        LIMIT 1
    ) AS total
FROM table
WHERE created_at BETWEEN "2017-02-20" AND "2017-03-01"
GROUP BY created_at
ORDER BY created_at DESC

它也是一张大桌子,因此找到一种高效的方法也很重要。

1 个答案:

答案 0 :(得分:1)

首先,您确定created_at是日期而不是日期时间吗?这会产生很大的不同。

您可以使用两个级别的聚合来执行您想要的操作:

SELECT SUM(max_total) AS total, DATE_FORMAT(created_at, '%d/%m/%Y') AS date
FROM (SELECT t.customer_id, t.created_at, MAX(total) as max_total
      FROM table t
      WHERE t.created_at BETWEEN '2017-02-20' AND '2017-03-01'
      GROUP BY t.customer_id, t.created_at
     ) t
GROUP BY created_at
ORDER BY created_at DESC;