I am trying to retrieve data from public.users tables and this the query I am using but I am not able to retrieve, what i actually require:
WITH duplicates AS (
SELECT email, COUNT(*) AS duplicate_count
FROM public.users
GROUP BY email
HAVING COUNT(*) > 1)
SELECT u.user_id, u.user_name, d.duplicate_count
FROM public.users u
JOIN duplicates d ON u.email = d.email
WHERE u.registration_date >= CURRENT_DATE - INTERVAL '30 days';
I am trying to use the concept of Common Table Expression (CTE) named "duplicates" to find all email addresses that have more than one occurrence in the "public.users" table. I might be making some mistake, because despite having duplicate emails I am not able to fetch them using this particular query. I will be grateful if you could help!
If you just want to get emails with entries during the last 30 days and a duplicate from any time:
Also assuming
registration_dateis an actualdate.If the table is big, with lots of older data, and duplicates often occur in close proximity, this more elaborate query might perform better:
This time also including details for the latest entry.