这是我的表:
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
答案 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
。
答案 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 |
+------+---------------------+-------+