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

Get the first created user per organization

SELECT email, org_id, MIN(created_at) as first_user_created
FROM users
WHERE org_id IN (SELECT org_id FROM subscriptions)
GROUP BY email, org_id;

Result of the above query gives me multiple user records per org_id.

What I want: Per organization – return the email, org_id and first_user_created of user that got created the earliest.

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 :

One solution uses DISTINCT ON:

SELECT DISTINCT ON (u.org_id) u.email, u.org_id, u.created_at
FROM users u
INNER JOIN subscriptions s
    ON s.org_id = u.org_id
ORDER BY u.org_id, u.created_at;

Another way to do this uses RANK():

WITH cte AS (
    SELECT u.email, u.org_id, u.created_at,
           RANK() OVER (PARTITION BY u.org_id ORDER BY u.created_at) rnk
    FROM users u
    INNER JOIN subscriptions s ON s.org_id = u.org_id
)

SELECT email, org_id, created_at
FROM cte
WHERE rnk = 1;
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