我正在尝试按每张桌子的最大时间戳数量的重量计算每位玩家的加权平均值
例如下表:
desk | player | amount | weight | timestamp
-----------------------------------
---- 1 --- | ---- 1 --- | ---------2------|-----10-------|13:00
---- 1 --- | ---- 1 --- | ---------1------|-----15-------|14:00
---- 2 --- | ---- 1 --- | ---------5------|-----20-------|13:00
---- 2 --- | ---- 1 --- | ---------3------|-----5-------|15:00
---- 3 --- | ---- 2 --- | ---------5------|-----6-------|13:00
---- 3 --- | ---- 2 --- | ---------2------|-----30-------|14:00
---- 4 --- | ---- 2 --- | ---------1------|-----10-------|15:00
---- 4 --- | ---- 2 --- | ---------6------|-----3-------|13:00
结果应该是:
**player | weigtedAmount**
---1---| 1.5 ((15/20)*1 + (5/20)*3)
---2---| 1.75 ((30/40)*2 + (10/40)*1)
我尝试了以下查询,但我认为我在某处错过了一些timestamp = max(timestamp):
select player,SUM(lates_data.amount * (lates_data.weight/ lates_data.sumWeight))
from (SELECT *
FROM (select player as plr, SUM(weight) as sumWeight
from playersDb.player_stats
group by plr
) t1 INNER JOIN
(select desk, player, amount, weight
from playersDb.player_stats
group by desk, player
) t2
ON t1.plr= t2.player
) lates_data
group by player
有什么想法吗?
拉兹
答案 0 :(得分:1)
这里有一些代码可以产生您所需的结果。
#DROP TABLE IF EXISTS deskWeight;
CREATE TABLE deskWeight (desk INT UNSIGNED, player INT UNSIGNED, amount INT UNSIGNED, weight INT UNSIGNED, `timestamp` TIME);
INSERT INTO deskWeight VALUES
(1, 1, 2, 10, '13:00'),
(1, 1, 1, 15, '14:00'),
(2, 1, 5, 20, '13:00'),
(2, 1, 3, 5, '15:00'),
(3, 2, 5, 6, '13:00'),
(3, 2, 2, 30, '14:00'),
(4, 2, 1, 10, '15:00'),
(4, 2, 6, 3, '13:00');
SELECT A.player, SUM(A.weight / B.weightSum * A.amount) weightedAmount FROM
(
SELECT A.player, B.weight, B.amount FROM
(
SELECT desk, player, MAX(`timestamp`) timestampMax FROM deskWeight GROUP BY desk, player
) A
INNER JOIN
deskWeight B
ON A.desk = B.desk AND A.player = B.player AND A.timestampMax = B.`timestamp`
) A
INNER JOIN
(
SELECT A.player, SUM(B.weight) weightSum FROM
(
SELECT desk, player, MAX(`timestamp`) timestampMax FROM deskWeight GROUP BY desk, player
) A
INNER JOIN
deskWeight B
ON A.desk = B.desk AND A.player = B.player AND A.timestampMax = B.`timestamp`
GROUP BY A.player
) B
ON A.player = B.player
GROUP BY player;
此致
詹姆斯
答案 1 :(得分:1)
谢谢!
我设法用这个查询做到了:
SELECT player, sum(aw)/sum(weight) as total, sum(weight) as weight, max(timestamp) as timestamp FROM
(
SELECT player, desk, amount*weight as aw, weight, timestamp FROM
(
(SELECT player as p1, desk as d1, max(timestamp) as maxTs FROM playersDb.player_stats group by player, desk) mts
inner join
(SELECT * FROM playersDb.player_stats) data
on data.player = mts.p1 and data.desk = mts.d1 and data.timestamp = mts.maxTs
)
) t
group by player
拉兹