Return Most recent date per Column?

Asked

Viewed 78 times

1

I have this table in `Mariadb [accounts]>

SELECT * FROM mercado WHERE nome_mercado LIKE 'extra';

+----+--------------+-------------+-----------+-----------+-------+
| id | nome_mercado | data_compra | produto   | descricao | preco |
+----+--------------+-------------+-----------+-----------+-------+
|  1 | Extra        | 2017-07-12  | Coca Cola | Coca      |  3.00 |
|  2 | Extra        | 2017-07-12  | Sucos     | Suco      |  3.50 |
|  3 | Extra        | 2017-07-12  | Frios     | Frios     |  7.80 |
| 11 | extra        | 2017-07-28  | Suco      | Teste     |  5.90 |
| 12 | extra        | 2017-07-28  | Bolacha   |           |  2.49 |
+----+--------------+-------------+-----------+-----------+-------+`

I would like you to return only the products with the latest dates, that is, only these:

| 11 | extra        | 2017-07-28  | Suco      | Teste     |  5.90 |
| 12 | extra        | 2017-07-28  | Bolacha   |           |  2.49 |

I used this select, but it returns nothing:

Mariadb [accounts]>

SELECT * FROM mercado WHERE nome_mercado LIKE 'extra' = 
  (SELECT data_compra FROM mercado ORDER BY data_compra DESC LIMIT 1);

Empty set, 5 warnings (0.00 sec)

3 answers

3

You can create a WHERE to return the results of the last 3 days, for example:

WHERE data_compra >= DATE(NOW()) - INTERVAL 3 DAY

If it is longer, only you edit the interval.

To query returns all results that have the nome_mercado as extra and the last records of the last 3 days. See:

SELECT * FROM mercado WHERE nome_mercado LIKE 'extra' AND data_compra >= DATE(NOW()) - INTERVAL 3 DAY ORDER BY data_compra DESC
  • I would put this Where in the second select? , after the "=" ?

  • @user54154 see edition.

3


If you always want the items of the last purchase do so:

select 
  * 
from 
  MERCADO 
where 
  NOME_MERCADO like 'extra'
  and DATA_COMPRA = 
  (
      select 
        max(DATA_COMPRA) 
      from 
        MERCADO 
      where 
        NOME_MERCADO like 'extra'
  )

This is what you wanted?

Example sqlfiddle

http://sqlfiddle.com/#! 9/dc427d/1

  • That’s exactly what it was. Grateful!

  • Wouldn’t this subquery you placed be useless? In my view it can be simplified by just: max(DATA_COMPRA)

  • @Francisco you have to do another search. Your idea here http://sqlfiddle.com/#! 9/ebfb84/3 is correct here http://sqlfiddle.com/#! 9/dc427d/1

2

No need to subquery, just do everything together:

SELECT * FROM mercado WHERE nome_mercado LIKE 'extra' ORDER BY data_compra DESC LIMIT 2;
  • If the last purchase has 3 items? Does what?

  • @Marlontiedt I am answering what is asked in the question. For her it is not known if there is this variable.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.