How to return the last record of each sale

Asked

Viewed 24 times

2

How to return the last record of each sale considering the max(date)?

+---------+--------------------+---------------+
|venda    |Data                |id             |
+---------+--------------------+---------------|
|0000001  |2021-01-10 12:04:45 |0000000000001  |
|0000001  |2021-01-10 12:14:20 |0000000000002  |
|0000002  |2021-01-12 12:20:59 |0000000000003  |
|0000002  |2021-01-12 12:21:20 |0000000000004  |
|0000003  |2021-01-12 12:30:23 |0000000000005  |
|0000004  |2021-01-13 12:21:20 |0000000000006  |
|0000004  |2021-01-14 12:21:20 |0000000000007  |
|0000004  |2013-02-15 12:20:59 |0000000000008  |
+---------+--------------------+---------------+

SELECT
    *
FROM
    foo
WHERE
    DATA =(
        SELECT
            MAX( DATA )
        FROM
            foo
    )

this select I did returns only the last row of everything and should return:

+---------+--------------------+---------------+
|venda    |Data                |id             |
+---------+--------------------+---------------|
|0000001  |2021-01-10 12:14:20 |0000000000002  |
|0000002  |2021-01-12 12:21:20 |0000000000004  |
|0000003  |2021-01-12 12:30:23 |0000000000005  |
|0000004  |2013-02-15 12:20:59 |0000000000008  |
+---------+--------------------+---------------+

1 answer

1

Try the following:

SELECT venda, max(data) from foo group by venda;
  • 1

    ball man show, that’s right. The secret was in group by that I didn’t pay attention to. Thank you, helped a young man acquire a new knowledge. Thanks again.

  • You’re welcome @Hugoleonardo, good luck

Browser other questions tagged

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