Skip to content
Advertisement

Retrieve the first data from multiple almost the same or correct data in table

How can i retrieve a data from query that has multiple the same data?. Something like this. I have a data representation like this:

Id        Time              Status
-------------------------------------
1   2019-09-09 09:00:00       1
2   2019-09-09 09:02:36       1
3   2019-09-09 09:06:00       1
4   2019-09-09 09:10:11       1
5   2019-09-09 17:00:00       2
6   2019-09-09 17:05:00       2
7   2019-09-10 09:00:00       1
8   2019-09-10 09:02:32       1
9   2019-09-10 09:02:38       1
10   2019-09-10 17:00:00       2
11   2019-09-10 17:00:30       2

Now i want to return something like these with parameter where date = 2019-09-09 :

1   2019-09-09 09:00:00       1
5   2019-09-09 17:00:00       2

i want to return the first data that was inserted.

Advertisement

Answer

Using ROW_NUMBER:

SELECT id, Time, Status
FROM
(
    SELECT *, ROW_NUMBER() OVER (PARTITION BY Status ORDER BY Time) rn
    FROM yourTable
    WHERE Time >= '2019-09-09' AND Time < '2019-09-10'
) t
WHERE rn = 1
ORDER BY Status;

If you are using a version of MySQL earlier than 8+, then use:

SELECT t1.id, t1.Time, t1.Status
FROM yourTable t1
INNER JOIN
(
    SELECT Status, MIN(Time) AS min_time
    FROM yourTable
    WHERE Time >= '2019-09-09' AND Time < '2019-09-10'
    GROUP BY Status
) t2
    ON t1.Status = t2.Status AND t1.Time = t2.min_time
WHERE
    t1.Time >= '2019-09-09' AND t1.Time < '2019-09-10'
ORDER BY
    t1.Status;
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement