Create mysql function on repeated dates

0

I need to create a function which takes the dates of a table and if there are 2 repeating ids, it takes the most recent date.

For example:

Usuario_ID|Video_ID|Fecha

11        |1       |2018-05-12

11        |1       |2018-05-13

11        |1       |2018-05-15

And that shows only "2018-05-15"

    
asked by Gustavo Leon Santos 20.07.2018 в 03:09
source

2 answers

2

You can do it in the following way:

  • Using MAX to select the maximum date
  • Grouping with GROUP BY per user, and also by video? (That part is not clear in the question, but you only have to add to the list of GROUP BY all those columns for which you want to group).

Grouping by user and video:

SELECT 
     usuario_id, 
     video_id, 
     max(fecha) fecha  
 FROM videos_fechas_20180719  
 GROUP BY usuario_id,video_id;

Result:

usuario_id     video_id      fecha
--------------------------------------------------
    11             1         15.05.2018 00:00:00

Grouping only by user:

 SELECT 
     usuario_id, 
     max(fecha) fecha  
 FROM videos_fechas_20180719  
 GROUP BY usuario_id;

Result:

usuario_id     fecha
--------------------------------------------------
    11         15.05.2018 00:00:00

Grouping by video:

 SELECT 
     video_id, 
     max(fecha) fecha  
 FROM videos_fechas_20180719  
 GROUP BY video_id;

Result:

video_id       fecha
--------------------------------------------------
    1          15.05.2018 00:00:00
    
answered by 20.07.2018 в 04:35
0
  

I propose the following answer, with an example to try   guide you and adapt it to your needs

I have a table with an id and dates

MariaDB [demo]> SELECT id, fecha FROM dates;
+------+------------+
| id   | fecha      |
+------+------------+
|    1 | 2018-01-12 |
|    1 | 2018-01-11 |
|    1 | 2018-01-10 |
|    2 | 2018-01-11 |
+------+------------+

Later as you can see I have three dates registered with the same id, but I only want the most recent one

MariaDB [demo]> SELECT id, fecha FROM dates WHERE fecha = (SELECT MAX(fecha) FROM dates);
+------+------------+
| id   | fecha      |
+------+------------+
|    1 | 2018-01-12 |
+------+------------+
  

What I did was first select the columns id and date of the   table dates but with the clause WHERE I indicate that it will only do   when you select the maximum registration date; that to achieve that   I use a subquery and the aggregation function MAX

UPDATE

For the specific case of your query, more or less it should be this way

SELECT Usuario_ID, Video_ID, Fecha 
FROM tablaName 
WHERE Fecha = (SELECT MAX(Fecha) FROM tablaName);
    
answered by 20.07.2018 в 03:32