简体   繁体   中英

Sql Query to obtain unique values from a mixed data

I am new to MySql and have been trying to learn it for a project. I have a table as below (Table 1) and I need the output from it as Table 2.

Table 1: Input Table
+----+----------+-----+-----------+----------+
| ID | FRUIT_TYPE    | FRUIT      | CREATED_AT   
+----+----------+-----+-----------+----------+
|  1 | Drupes        |  plums     | 2020-06-12 25:10:10
|  2 | Drupes        |  peaches   | 2020-06-11 25:10:10
|  3 | Drupes        |  olives    | 2020-06-11 24:10:10
|  4 | Berries       |  grapes    | 2020-06-08 25:10:10
|  5 | Pomes         |  apples    | 2020-06-07 25:10:10
|  6 | Pomes         |  pears     | 2020-06-05 25:10:10
|  7 | Hesperidia    |  lemons    | 2020-06-05 24:10:10
|  8 | Hesperidia    |  oranges   | 2020-06-05 23:10:10
+----+----------+-----+-----------+----------+
Table 2: Final Output Desired 
+----+----------+-----+-----------+----------+
| ID | FRUIT_TYPE    | FRUIT      | CREATED_AT   
+----+----------+-----+-----------+----------+
|  3 | Drupes        |  olives    | 2020-06-11 24:10:10
|  4 | Berries       |  grapes    | 2020-06-08 25:10:10
|  6 | Pomes         |  pears     | 2020-06-05 25:10:10
|  8 | Hesperidia    |  oranges   | 2020-06-05 23:10:10
+----+----------+-----+-----------+----------+

The output is ordered by CREATED_AT field and if there are multiple rows for the same FRUIT_TYPE, the field with the least CREATED_AT value is picked.

For e..g of the 3 values for Drupes, only 1 row is taken where FRUIT is olives and the CREATED_AT values is the least.

If you put out the sql query, do explain it. :P Thanks in advance !

A simple method is a correlated subquery:

select t.*
from t
where t.created_at = (select min(t2.created_at)
                      from t t2
                      where t2.fruit_type = t.fruit_type
                     );

With an index on (fruit_type, created_at) , this is likely to be the most performant method as well.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM