考慮以下...爲同一
CREATE TABLE my_table
(id INT NOT NULL AUTO_increment primary key
, result varchar(12)
, winnings int
, multi int
);
insert into my_table values
(1 ,'win', 2 , 8550),
(2 ,'lose', 0 , 8550),
(3 ,'win', 2 , 6990),
(4 ,'win', 5 , 6990),
(5 ,'win', 12 , 1443),
(6 , 'lose', 0 , 2201);
select x.result
, sum(z.winnings) total
, x.multi
from my_table x
join
(SELECT MULTI
, MAX(ID) max_id
FROM MY_table
group
by multi
) y
on y.multi = x.multi
and y.max_id = x.id
join my_table z
on z.multi = x.multi
and z.result = x.result
group
by x.multi, x.result;
+--------+-------+-------+
| result | total | multi |
+--------+-------+-------+
| win | 12 | 1443 |
| lose | 0 | 2201 |
| win | 7 | 6990 |
| lose | 0 | 8550 |
+--------+-------+-------+
小提琴:http://sqlfiddle.com/#!9/9a31e/3
編輯:粗擴展這個想法 - 返回丟失/ 0,如果多發生任何損失...
SELECT COALESCE(b.result,a.result) result
, COALESCE(b.winnings,a.total) total
, a.multi
FROM
(
select x.result
, sum(z.winnings) total
, x.multi
from my_table x
join
(SELECT MULTI
, MAX(ID) max_id
FROM MY_table
group
by multi
) y
on y.multi = x.multi
and y.max_id = x.id
join my_table z
on z.multi = x.multi
and z.result = x.result
group
by x.multi, x.result
) a
LEFT JOIN my_table b
ON b.multi = a.multi
AND b.result = 'lose';
8550 gewonnen發生了什麼事? – Strawberry
此外結果表似乎是多餘的。 0總是等於'輸' – Strawberry
http://sqlfiddle.com/#!9/9a31e/3 – Strawberry