My query is taking too long to finish for finding the pair of rows where the difference of columns value is maximum group by another column

后端 未结 4 1242
醉话见心
醉话见心 2021-01-26 19:10

Say, I\'ve a table like this:

I want to find the pair of Centers whose Performance difference is highest for each session, like this:

I have th

4条回答
  •  时光说笑
    2021-01-26 19:33

    Grouping by session and taking the group's min and max performance seems logical. The actual centers unfortunately need a subquery/join here.

    select g.session as Session,
        (select min(center) from mytable
         where session = g.session and performance = g.maxim) as Center1,
        (select min(center) from mytable
         where session = g.session and performance = g.minim) as Center2,
        g.maxim - g.minim as Performance
    from (select 
            t1.session,
            min(t1.performance) as minim,
            max(t1.performance) as maxim
        from mytable t1
        group by t1.session)
        as g
    

    Ensure an index on session and performance.

提交回复
热议问题