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:
>Solution :
- You need to do an
INNER JOINback onto the initial results. - DBFiddle: https://www.db-fiddle.com/f/araAeTfLPr32Mv636Y7SaJ/0
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:

