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 do I select and join from a single table with 2 unique IDs based on one ID and concatenate the options?

I don’t have much experience with SQL so forgive me if it is a simple answer…

I am working on a personal project in Python and I am using sqlite3. I currently have a table created like this:

CREATE TABLE IF NOT EXISTS table (id text, username text, score integer, UNIQUE(id,username))

where the idea is two users can score the same ID differently, and also the same user can score multiple ID’s.

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

ID Username Score
1 User1 5
1 User2 7
1 User3 10
2 User1 6
2 User2 2

How to I select to find common ID’s among users as well as their scores? Is there a select command I can string up to return something like this? (i.e. common between users User1 and User2)

ID Score User1 Score User2
1 5 7
2 6 2

>Solution :

Use conditional aggregation:

SELECT id,
       MAX(CASE WHEN username = 'User1' THEN score END) ScoreUser1,
       MAX(CASE WHEN username = 'User2' THEN score END) ScoreUser2
FROM tablename
WHERE username IN ('User1', 'User2')
GROUP BY id;

See the demo.

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