Mysql查询-使用分组依据和最大时间戳进行加权平均

myzjeezk  于 2022-12-28  发布在  Mysql
关注(0)|答案(2)|浏览(146)

我尝试通过每个桌面的最大时间戳金额的权重来计算每个玩家金额的加权平均值
例如下表:

table|播放器|数量|重量|时间戳

  • ---一---| - ---一---| - -------2-----| -----10-------| 13点整
  • ---一---| - ---一---| - -------1-----| -----15-------| 14点整
  • ---二---| - ---一---| - -------5------| -----20-------| 13点整
  • ---二---| - ---一---| - -------3------| -----5-------| 15点整
  • -三---| - ---二---| - -------5------| -----6-------| 13点整
  • -三---| - ---二---| - -------2-----| -----30-------| 14点整
  • -四---| - ---二---| - -------1-----| -----10-------| 15点整
  • -四---| - ---二---| - -------六------| -----3-------| 13点整
    结果应该是:
    • 玩家|加权金额**

---1---| 1.5((15/20)* 1+(5/20)* 3)
---2---| 1.75((30/40)* 2+(10/40)* 1)
我尝试了下面的查询,但我认为我在某处丢失了一些时间戳= 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

你知道吗?
拉兹

3bygqnnd

3bygqnnd1#

下面是一些代码,它们应该可以生成您所需的结果。

#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;

此致,
詹姆斯

vsmadaxz

vsmadaxz2#

谢谢!
我设法用这个查询做到了这一点:

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

拉兹

相关问题