MYSQL在group by中有共同记录

时间:2016-07-01 14:21:58

标签: mysql group-by aggregate-functions

这是我的表:

user     presenter   price  
------  ------------  --------
84            84      5000
88            84      3000
89            84      4000
89            84      7000

我将按user对此表进行分组,并为每个用户总计price,还包括presenter id等于user <的行登记/> 最终结果应该是:

user          total_price  
------    ------------------
84        5000 + 3000 + 4000 + 7000
88        3000
89        4000 + 7000

2 个答案:

答案 0 :(得分:2)

您可以使用UNION ALL

SELECT user, SUM(price) AS total_price
FROM (
  SELECT user, price
  FROM mytable

  UNION ALL

  SELECT presenter AS user, price
  FROM mytable AS t1
  WHERE presenter <> user AND
        EXISTS (SELECT 1
                FROM mytable AS t2
                WHERE t1.presenter = t2.user)) AS t
GROUP BY user

第二个查询会向user个数据追加presenter同时为user的所有记录。外部查询仅使用GROUP BY,以便按SUM计算price user

Demo here

答案 1 :(得分:2)

这个解决方案对你的数据集做了一个严肃的假设,这可能很容易被假(可能是!)......

DROP TABLE IF EXISTS my_table;

CREATE TABLE my_table
(id INT NOT NULL AUTO_INCREMENT PRIMARY KEY
,user INT NOT NULL
,presenter INT NOT NULL
,price  INT NOT NULL
);

INSERT INTO my_table (user,presenter,price) VALUES
(84,84,5000),
(88,84,3000),
(89,84,4000),
(89,84,7000);

SELECT user
     , GROUP_CONCAT(price) prices
     , SUM(price) total 
  FROM 
     ( SELECT user
            , price 
         FROM my_table
        UNION
       SELECT presenter
            , price 
         FROM my_table
     ) x 
 GROUP 
    BY user;
+------+---------------------+-------+
| user | prices              | total |
+------+---------------------+-------+
|   84 | 5000,3000,4000,7000 | 19000 |
|   88 | 3000                |  3000 |
|   89 | 4000,7000           | 11000 |
+------+---------------------+-------+