Home >Database >Mysql Tutorial >How to Find the Most Recent Position for Each Security Using SQL?

How to Find the Most Recent Position for Each Security Using SQL?

Susan Sarandon
Susan SarandonOriginal
2025-01-04 12:43:41942browse

How to Find the Most Recent Position for Each Security Using SQL?

Groupwise Maximum

Problem:

Obtain the latest position for each security from the following table:

id security buy_date
26 PCS 2012-02-08
27 PCS 2013-01-19
28 RDN 2012-04-17
29 RDN 2012-05-19
30 RDN 2012-08-18
31 RDN 2012-09-19
32 HK 2012-09-25
33 HK 2012-11-13
34 HK 2013-01-19
35 SGI 2013-01-17
36 SGI 2013-02-16
KERX 2013-02-20
KERX 0000-00-00

Solution:

The following query retrieves the maximum buy date for each security, along with the corresponding ID:

SELECT p1.id, 
       p1.security, 
       p1.buy_date 
       FROM positions p1
left join
            positions p2
                on p1.security = p2.security
                   and p1.buy_date < p2.buy_date
      where 
      p2.id is null;

This query efficiently finds the latest position for each security using a left join. It compares the buy dates of each security and only selects rows where no later buy date exists. This optimized solution ensures accurate results in a faster execution time compared to subquery-based approaches.

The above is the detailed content of How to Find the Most Recent Position for Each Security Using SQL?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn