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 1251
醉话见心
醉话见心 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条回答
  •  -上瘾入骨i
    2021-01-26 19:43

    select 
            t1.session,
            t1.center center1,
            t2.center center2,
            t1.performance - t2.performance performance
        from mytable t1
        inner join mytable t2 
           on t1.session = t2.session
        WHERE t1.performance = (SELECT MAX(performance) 
                                FROM mytable t3 WHERE t3.session = t1.session)
          AND t2.performance = (SELECT MIN(performance) 
                                FROM mytable t3 WHERE t3.session = t2.session)
    
         // Im thinking this will solve the border case when performance is a tie 
         // and difference 0 will return 2 rows
    
         AND (CASE WHEN t1.performance = t2.performance 
                   THEN CASE WHEN t1.center < t2.center
                             THEN 1
                             ELSE 0
                        END
                   ELSE 1
              END) = 1
    

    As long as you have an index on performance and session should be fine.

提交回复
热议问题