Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

selecting most recent record

How to select most recent records if the records are having almost same kind of data...

example:

col1       col2          col3              col4
--------------------------------------------------
123         abc          1.1               12345
123         abc          1.1               123445
1234        dsv          2.0               123
1234        dsv          2.0               1233
12345       dsvw         1.2               1234

The maximum of col4 when it compares with rest of the columns.

See the row1 and row2 data looks similar but we need the latest data based on col4.

Same thing with row3 and row4, data looks similar but we need the latest data based on col4.

And the required output is:

col1    col2   col3   col4
----------------------------
123     abc    1.1    123445
1234    dsv    2.0    1233
12345   dsvw   1.2    1234 
like image 360
Shahsra Avatar asked Jul 07 '11 21:07

Shahsra


People also ask

How do I select most recent records in SQL?

Use the aggregate MAX(signin) grouped by id. This will list the most recent signin for each id . To get the whole single record, perform an INNER JOIN against a subquery which returns only the MAX(signin) per id. Save this answer.

How do I find the latest query record?

To get the last record, the following is the query. mysql> select *from getLastRecord ORDER BY id DESC LIMIT 1; The following is the output. The above output shows that we have fetched the last record, with Id 4 and Name Carol.

How do I select the last 5 records of a table?

METHOD 1 : Using LIMIT clause in descending orderof specified rows from specifies row. We will retrieve last 5 rows in descending order using LIMIT and ORDER BY clauses and finally make the resultant rows ascending. Since Employee table has IDs, we will perform ORDER BY ID in our query.


1 Answers

I'm assuming that "latest" means "largest"?

DECLARE @t TABLE
(
    col1 INT, 
    col2 CHAR(3), 
    col3 DECIMAL(4,1), 
    col4 INT
);

INSERT @t SELECT 123, 'abc', 1.1, 12345
UNION SELECT 123, 'abc', 1.1, 123445
UNION SELECT 1234, 'dsv', 2.0, 123
UNION SELECT 1234, 'dsv', 2.0, 1233;

WITH t AS
(
    SELECT col1, col2, col3, col4,
        rn = ROW_NUMBER() OVER
            (PARTITION BY col1 ORDER BY col4 DESC)
        FROM @t
)
SELECT col1, col2, col3, col4
    FROM t
    WHERE rn = 1;
like image 95
Aaron Bertrand Avatar answered Oct 18 '22 18:10

Aaron Bertrand