Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can you suggest how to write this Query

I want to merge these two tables and want distinct email based on latest execution date(ExecDate)

WITH cte_1 AS (
        
    SELECT
        Requester_Emails,
        Region,
        ExecDate 
    FROM
        monthly_tickets 
    WHERE
        Region LIKE 'new%' 
        AND
        Region IS NOT NULL
    
    UNION
        
    SELECT
        Requester_Emails,
        Region,
        ExecDate 
    FROM
        weekly_tickets 
    WHERE
        Region LIKE 'new%' 
        AND
        Region IS NOT NULL
),
cte_2 AS (
    SELECT
        *
    FROM
        cte_1
    ORDER BY
        ExecDate
)
SELECT
    DISTINCT( Requester_Emails ),
    Region
FROM
    cte_2

Sample input and output data:

enter image description here

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

WITH ticketsUnion AS (
        
    SELECT
        Requester_Emails,
        Region,
        ExecDate 
    FROM
        monthly_tickets 
    WHERE
        Region LIKE 'new%'
    
    UNION
        
    SELECT
        Requester_Emails,
        Region,
        ExecDate 
    FROM
        weekly_tickets 
    WHERE
        Region LIKE 'new%'
),
latestDateByEmail AS (
    SELECT
        Requester_Emails,
        MAX( ExecDate ) AS maxExecDate
    FROM
        ticketsUnion
    GROUP BY
        Requester_Emails
)
SELECT
    ticketsUnion.Requester_Emails,
    ticketsUnion.Region,
    ticketsUnion.ExecDate
FROM
    latestDateByEmail
    INNER JOIN ticketsUnion ON
        latestDateByEmail.maxExecDate = ticketsUnion.ExecDate
        AND
        latestDateByEmail.Requester_Emails = ticketsUnion.Requester_Emails
ORDER BY
    ticketsUnion.Requester_Emails;

Screenshot proof:

enter image description here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading