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

Combining two mostly identical rows in SQL

I have a table that contains data like below:

Name ID Dept
Joe 1001 Accounting
Joe 1001 Marketing
Mary 1003 Administration
Mary 1009 Accounting

Each row is uniquely identified with a combo of Name and ID. I want the resulting table to combine rows that have same Name and ID and put their dept’s together separated by a comma in alpha order. So the result would be:

Name ID Dept
Joe 1001 Accounting, Marketing
Mary 1003 Administration
Mary 1009 Accounting

I am not sure how to approach this. So far I have this, which doesn’t really do what I need:

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 Name, ID, COUNT(*)
FROM employees
GROUP BY Name, ID

I know COUNT(*) is irrelevant here, but I am not sure what to do. Any help is appreciated! By the way, I am using PostgreSQL and I am new to the language.

>Solution :

Apparently there is an aggregate function for string concatenation with PostgreSQL. Find documentation here. Try the following:

SELECT Name, ID, string_agg(Dept, ', ' ORDER BY Dept ASC) AS Departments
FROM employees
GROUP BY Name, ID
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