我的MySQL结构是:
id Ergebnis gewinn multi
1 gewonnen 2 8550
2 verloren 0 8550
3 gewonnen 2 6990
4 gewonnen 5 6990
5 gewonnen 12 1443
6 verloren 0 2201
我需要从gewinn
计算得到的值,其中多个相同,但仅当ergebnis == gewonnen
(对于具有相同多值的所有人),如果一个或全部ergebnis = verloren
总数multi == verloren
。所以对于这个例子,正确的输出将是:
8550 == verloren / 0
6990 == gewonnen / 7
1443 == gewonnen / 12
2201 == verloren / 0
答案 0 :(得分:0)
考虑以下内容......
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';
答案 1 :(得分:0)
如果您将插入更改为:
insert into my_table values
(1 ,'lose', 0 , 8550),
(2 ,'win', 2 , 8550),
(3 ,'win', 2 , 6990),
(4 ,'win', 5 , 6990),
(5 ,'win', 12 , 1443),
(6 , 'lose', 0 , 2201);
结果是例如:8550 - >赢得 但应该失败。 如果任何id具有相同的multi ==输掉完整的multi应该是结果丢失