Home > Software design >  Combining two mostly identical rows in SQL
Combining two mostly identical rows in SQL

Time:02-17

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:

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.

CodePudding user response:

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
  • Related