如何在同一个表上按user_id汇总(金额)和分组

时间:2014-06-21 17:06:36

标签: mysql sql

我有一个每个user_id有很多行的表

我正在尝试按user_id对行进行分组并将其数量相加

这是表结构

Name    Type    Collation   Attributes  Null    Default Extra   Action
 1  user_id int(11)         No          None         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 2  amount  decimal(16,8)   No          None         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 3  aff int(11)             No             0         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 4  jackpot int(11)         No             0         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 5  paidout int(11)         No             0         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 6  type    int(11)         No             0         Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More
 7  created timestamp       No   CURRENT_TIMESTAMP   Change Change   Drop Drop   Browse distinct values Browse distinct values   Primary Primary     Unique Unique  Show more actions More

我正在尝试此查询但未成功:

  

更新trans   SELECT * FROM trans group by user_id   设定金额=(从转移中选择总和(金额)

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

您可以这样做:

UPDATE trans t
    INNER JOIN (
        select user_id, sum(amount) sumAmount
        from trans
        group by user_id
    ) subSum on subSum.user_id = t.user_id
SET t.amount = subSum.sumAmount

使用user_id范围:

UPDATE trans t
    INNER JOIN (
        select user_id, sum(amount) sumAmount
        from trans
        where user_id BETWEEN 0 AND 1000 --Edited
        group by user_id
    ) subSum on subSum.user_id = t.user_id
SET t.amount = subSum.sumAmount
WHERE t.user_id BETWEEN 0 AND 1000 --HEre

使用临时表

使用临时表:

--Create table with user_id and sum amount
CREATE TABLE trans_temp_sum_amount 
SELECT user_id, sum(amount) sumAmount
FROM trans
GROUP BY user_id;

--Update
UPDATE trans t
    INNER JOIN trans_temp_sum_amount subSum 
        on subSum.user_id = t.user_id
SET t.amount = subSum.sumAmount;

--Drop temp table 
DROP TABLE trans_temp_sum_amount;

答案 1 :(得分:0)

我建议您使用VIEW而不是“删除”所有数据:

CREATE VIEW trans_view AS
SELECT user_id, SUM(amount) FROM trans GROUP BY user_id;

我建议你看一下你的程序,并尝试每次更改amount时更新,而不是每次都插入一个新行。