【问题标题】:Finding the average of values, under the condition a column index appears more than once (mySQL))查找值的平均值,在列索引出现多次的条件下(mySQL)
【发布时间】:2014-12-22 16:10:17
【问题描述】:

我正在建立一个赛马数据库,并想查找是否有任何赛道比其他赛道更快/更慢。我不想只比较每条赛道的平均比赛时间,因为有些赛道中经验较少和速度较慢的马比例较高。为了避免这个错误,我想只使用在两条赛道上都参加过比赛的马匹来比较每条赛道。

到目前为止,我的表格包含

位置、马匹、平均时间

我想创建一个视图,在第一列中包含每个位置的单个条目。然后我希望每个位置都有自己的列,其中包含仅在两个位置比赛过的马匹的平均时间差异

例如,我希望输出看起来像这样:

╔═══════════╦═════════╦═════════╦══════␕╗ ║.......位置........ ║ .....fleming.... ║ ....morphet.... ║ ..caulfield... ... ║
╠═══════════╬═════════╬═════════╬═════════════════════> ║ .......弗莱明............║............ 0............║............- 0.1…………║…………-0.2…………║
║ .......多音段.......║............0.1............║............0. ……║…………0.3…………║
║ .......考菲尔德...... ║............0.2............║............-0.3...... .....║.......0.......║
╚═══════════╩═════════╩═════════╩════════════════
p>


到目前为止,我所拥有的是

选择位置,
(案例h_adv.location 当'弗莱明'然后h_adv.AVG_TIME END)) AS fleming,
(案例h_adv.location 当'morphet'然后h_adv.AVG_TIME END)) AS morphet,
(案例h_adv.location 当'考菲尔德'然后h_adv.AVG_TIME END)) AS caulfield,


但是我不知道如何指定我只想使用在两条赛道上比赛的马匹的时间,并且我想找到这些平均值之间的差异。任何帮助,将不胜感激。很抱歉这种格式。提前致谢。

【问题讨论】:

    标签: mysql average


    【解决方案1】:

    执行此操作的更多“SQL”方式是将数据放在行中而不是列中。假设没有一匹马在同一条赛道上比赛超过一次:

    select a1.location, a2.location, count(*) as num, avg(time)
    from h_adv a1 join
         h_adv a2
         on a1.horse = a2.horse 
    group by a1.location, a2.location;
    

    如果马匹在给定的赛道上比赛不止一次,那么您需要按马匹和赛道预先汇总数据。否则,您会得到一点笛卡尔积,这会导致平均值偏离:

    select a1.location, a2.location, count(*) as num, sum(sumtime) / count(*) as avg
    from (select location, horse, count(*) as numraces, sum(time) as sumtime
          from h_adv
          group by location, horse
         ) a1 join
         (select location, horse, count(*) as numraces, sum(time) as sumtime
          from h_adv
          group by location, horse
         ) a2
         on a1.horse = a2.horse 
    group by a1.location, a2.location;
    

    SQL 往往不擅长聚合时间。最好将时间存储为数字,例如秒数。

    【讨论】:

    • 啊,好吧,我现在取得了一些进展。是的,每个位置和马只有一个条目,因为我已经找到了每个位置的平均值。时间也已经使用双精度值存储为秒数。感谢您的帮助。
    猜你喜欢
    • 2018-07-12
    • 2022-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-02
    • 2014-10-08
    • 2020-08-10
    • 2022-11-15
    相关资源
    最近更新 更多