Search code examples
mysqlsqlselectsubquerymin

How to select max and min of 1 column based on other 2 columns?


I'm trying to get the max and min date values in column C based on the (column A, column B) unique pair combinations.

Suppose I have a table like:

column_A column_B column_C
A        1        2019-08-11
A        1        2018-11-12
A        1        2017-11-12
A        11       2020-03-03
A        11       2021-01-10
A        11       2021-02-02
B        2        2020-11-11
B        2        2020-12-12

The output I want to get is:

column_A column_B column_C
A        1        2019-08-11
A        1        2017-11-12
A        11       2020-03-03
A        11       2021-02-02
B        2        2020-11-11
B        2        2020-12-12

My attempt query has been taking 20 mins to run with no output yet (just tried to get max date from column C for now):

SELECT column_A, column_B, column_C FROM table_name
WHERE column_C IN (
   SELECT MAX(column_C) FROM table_name
   GROUP BY column_A, column_B
)

Solution

  • Just use two conditions:

    select t.*
    from t
    where column_c = (select max(t2.colc)
                      from table_name t2
                      where t2.column_A = t.column_A and t2.column_B = t.column_B
                     ) or
          column_c = (select min(t2.colc)
                      from table_name t2
                      where t2.column_A = t.column_A and t2.column_B = t.column_B
                     ) ;