Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in SQL by (20.3k points)

I have a table that is a collection entry as to when a user was logged on.

username, date,      value

--------------------------

brad,     1/2/2010,  1.1

fred,     1/3/2010,  1.0

bob,      8/4/2009,  1.5

brad,     2/2/2010,  1.2

fred,     12/2/2009, 1.3 etc..

How do I create a query that would give me the latest date for each user?

Update: I forgot that I needed to have a value that goes along with the latest date.

2 Answers

0 votes
by (40.7k points)

Try using the below code:

Query

select t.username, t.date, t.value

from MyTable t

inner join (

    select username, max(date) as MaxDate

    from MyTable

    group by username

) tm on t.username = tm.username and t.date = tm.MaxDate

You can master these queries and become proficient in SQL queries by enrolling in an industry-recognized SQL certification

0 votes
by (3.1k points)

In order to get the latest record date for every user in the system along with the related value from the user logins particulars table, it is necessary to use either a Subquery or a Common Table Expression Restatement (CTE). The CTE implementation entails the entry of the function ROW_NUMBER() in that it allows for the ordering of any sub - set of results in a desired order, with the ordering done concerning an appropriate column, in this case, dates starting with the earliest date. This means that the row number which is assigned for every user within the subset will be 1 in the row that is associated with the most recent entry. Notwithstanding the use of CTE, one can also go a step further and use a simpler query method whereby the records are being queried are already dated at the maximum possible date for the particular user in order to retrieve those records and their respective values only. Either way, the expectation is achieved.

Using CTE 

WITH LatestLogins AS (

    SELECT 

        username, 

        date, 

        value,

        ROW_NUMBER() OVER (PARTITION BY username ORDER BY date DESC) AS rn

    FROM 

        your_table_name

)

SELECT 

    username, 

    date, 

    value

FROM 

    LatestLogins

WHERE 

    rn = 1;

Using SubQuery

SELECT 

    t.username, 

    t.date, 

    t.value

FROM 

    your_table_name t

WHERE 

    t.date = (SELECT MAX(date) 

               FROM your_table_name 

               WHERE username = t.username);

1.2k questions

2.7k answers

501 comments

693 users

Browse Categories

...