Search code examples
mysqlsqlms-access-2010minimum

SQL: How to add a column with the minimum value


I would appreciate your support, I'd like to build a SQL qry to obtain as result an additional comlumn with the minimum value of group of codes based on 2 tables.

For example:I have 2 tables

Table: extract

AppCode | Phase |
------------------ 
AB | Phase 2
ABC | Phase 1
ABC | Phase 2
ABCD | Phase 1
ABCE | Phase 3
ABCE | Phase 2 

Table: Phases

PhaseName | Objective
------------------
Phase 1 | 2
Phase 2 | 4
Phase 3 | 24

Output expected:

AppCode |   PhaseName |  Objective |  MinObjetivo 
------------------
AB |       Phase 2 |        4 |            4
ABC |      Phase 1 |        2 |            2 
ABC |      Phase 2 |        4 |            2 
ABCD |     Phase 1 |        2 |            2
ABCE |     Phase 3 |        24 |           4
ABCE |     Phase 2 |        4 |            4

Please Let me know; if with this example is not enough


Solution

  • In MySQL:

    SELECT e.appcode, p.phasename, p.objective, m.minobjectivo
    FROM extract AS e
    JOIN phases AS p ON e.phase = p.phasename
    JOIN (SELECT e1.appcode, MIN(p1.objective) as minobjectivo
          FROM extract AS e1
          JOIN phases AS p1 ON e1.phase = p1.phasename
          GROUP BY e1.appcode) AS m
        ON e.appcode = m.appcode
    

    This starts out as an ordinary join between extract and phases, to get the first 3 columns. Then you write a subquery that gets the minimum objective for each appcode, and join this to get the additional column.

    DEMO

    Here's another way to write it:

    SELECT e.appcode, p.phasename, p.objective, MIN(p1.objective) AS minobjectivo
    FROM extract AS e
    JOIN phases AS p ON e.phase = p.phasename
    JOIN extract AS e1 ON e1.appcode = e.appcode
    JOIN phases AS p1 ON e1.phase = p1.phasename
    GROUP BY e.appcode, p.phasename
    

    This is similar, but the additional joins are done in the main query instead of a subquery.

    DEMO