MySQL - 行的SUM,按降序排列重复项

时间:2015-04-28 15:03:21

标签: mysql sql mysqli

我有一张表如下

+----+---------+-------------+--------+
| id | user_id | ip_address  | amount |
+----+---------+-------------+--------+
|  1 |       2 | 192.168.1.1 | 0.5    |
|  2 |       2 | 192.168.1.1 | 0.5    |
|  3 |       2 | 192.168.1.2 | 0.5    |
|  4 |       2 | 192.168.1.3 | 0.5    |
|  5 |       5 | 192.168.5.1 | 1.5    |
|  6 |       5 | 192.168.5.1 | 1.5    |
|  7 |       5 | 192.168.5.3 | 0.5    |
+----+---------+-------------+--------+

我希望获得ip_address的唯一amount和,并将重复项计为仅一个。

从上表中有7行,其中前4个记录用于user_id 2,最后3个记录用于user_id 5。

我正在尝试将amount字段的sum与user_id一起按降序排列,并希望输出如下。

user_id    total_amount
5          2.0
2          1.5

请帮我解决这个问题。

4 个答案:

答案 0 :(得分:2)

尝试这种方式:

select user_id, sum(amount)
from (select user_id, ip_address, amount
      from  tab 
      group by  ip_address, amount ) A
group by  user_id
order by  user_id desc

SqlFiddle演示

答案 1 :(得分:1)

GROUP BY,具有聚合函数SUM,位于DISTINCT行:

select user_id, sum(amount) as total_amount
from (select distinct user_id, ip_address, amount
      from tablename) t
group by user_id

不确定这是不是MySQL,而是测试和评论!

答案 2 :(得分:0)

我认为您必须使用子查询:

SELECT inner_query.user_id, SUM(inner_query.amount) FROM (
    SELECT * FROM  table_name GROUP BY user_id, ip_address ORDER BY user_id DESC 
) AS inner_query GROUP BY inner_query.user_id ORDER BY user_id DESC 

答案 3 :(得分:0)

这应该做你想要的我相信:

SELECT USER_ID, SUM(amount) AS Amount, COUNT(*) AS [COUNT] from
(SELECT DISTINCT user_id, ip_address, amount FROM mytable)q
GROUP BY q.user_id