Query to filter out data based on two logic This is a sample table:

  sample_id  |      timestamp       | p_id
============================================
    62054    |  2018-09-25 10:18:15 |  2652
    62054    |  2018-09-27 16:44:57 |  966
    62046    |  null                |  1809
    62046    |  2018-09-25 10:18:15 |  2097


We need to filter out unique sample_id column, but the logic is 


IF the timestamp column is null, then return those null column data

    62046 | null | 1809

IF the timestamp column is not null, then return the latest timestamp column data

 62054 | 2018-09-27 16:44:57 | 966



So its great if anyone provide the sql query.

We need somethings like that,

WHERE
IF(
    NOT NULL = all row group by sample_id,
    row where cancelled_at is maximum,
    null column
)
So we're grouping by the combination of the sample_id and wheither timestamp IS NULL. The max is returned the group. MAX(NULL) is NULL so that case is covered.

SELECT sample_id, MAX(timestamp)
FROM table
GROUP BY sample_id, timestamp IS NULL