Each schedule has many ramps, and each ramp has an `end_date`.

I need to list all my ramps, along with an extra field that contains the id of the ramp with the latest end date for that schedule. I also need to be able to use this extra field in my `WHERE` clause.

This is typically a case for a sub-query using the `MAX` function, except for one problem: the ramp's `end_date` field can be null, indicating the ramp is current. Thus, `SELECT MAX(end_date)` doesn't work, since `null` values are 'smaller' than non-null values.

So far, this is what I've come up with:

```
SELECT r1.*,
    (SELECT r2.id
    FROM ramp as r2
    WHERE schedule_id = r.schedule_id
    ORDER BY IF(end_dte is NULL, '9999-99-99', end_dte) DESC
    LIMIT 1) as latestId
FROM ramp as r1

```

This produces this table, which is exactly what I want:

```
+-------+-------------+------------+-----------------+--------+------------+------------+----------+
| id    | schedule_id | suppr_flag | comment         | months | start_dte  | end_dte    | latestId |
+-------+-------------+------------+-----------------+--------+------------+------------+----------+
|    16 |           7 | NULL       | NULL            |   NULL | 2008-06-23 | NULL       |       16 |
|    15 |           6 | NULL       | NULL            |   NULL | 2007-05-01 | 2007-12-31 |       15 |
|    13 |           5 | NULL       | 1-15 deals      |   NULL | 2004-08-11 | NULL       |       13 |
|    11 |           4 | NULL       | NULL            |   NULL | 2005-08-11 | NULL       |       11 |
|    12 |           4 | NULL       | NULL            |     12 | 2004-08-11 | 2005-08-10 |       11 |
|    17 |          13 | NULL       | NULL            |      6 | 2009-03-05 | 2009-09-04 |       19 |
|    18 |          13 | NULL       | NULL            |      6 | 2009-09-05 | 2010-03-04 |       19 |
|    19 |          13 | NULL       | NULL            |   NULL | 2010-03-05 | NULL       |       19 |
|    20 |          14 | NULL       | NULL            |     12 | 2001-06-18 | 2008-06-17 |       20 |

```

except I cannot use `latestId` in a WHERE clause (it's an unknown column).

Do you have any ideas?