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

How to get a single row where multiple rows share the same column value

Say I have an sql query that returns the following data:

USERID, LOCATIONID, SITE
usera, locationa, site1
userb, locationb, site1
userx, locationx, site1
userc, locationc, site2

I only care about unique SITE, so I would like the query to return:

USERID, LOCATIONID, SITE
usera, locationa, site1
userc, locationc, site2

How can I modify:

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

select userid, locationid, site from mytable order by site; 

To accomplish this?

>Solution :

You’re after a frequently asked solution for a top n rows per group

You can use a windowed row_number to assign a sequence to each group, here determined by the LocationId value:

with sites as (
  select userid, locationid, site,
    Row_Number() over(partition by site order by LocationId) rn
  from mytable
)
select userid, locationid, site
from sites
where rn = 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