简体   繁体   中英

Node / Postgres SQL Select distinct entries then put all other entries with the same reference into one column

this question was probably asked somewhere but I can't seem to phrase it correctly in the search to find an accurate answer.

I'm doing a query on a Postgres DB, it has quite a few joins, the results are something like this:

WON   |   name   |   item
1         Joe        A
1         Joe        B
2         Smith      A

So one row for each entry, I need to somehow get the result back as such:

WON   |   name   |   item
1         Joe        A, B
2         Smith      A

This can be done in the query or with NodeJS, there are hundreds to thousands of results for the query, so getting a distinct row (WON 1) then searching the DB for all entries that match it then repeating for the rest isn't feasible, so this may be better done in Node / Javascript, but I'm somewhat new to that, what would be a (somewhat) efficient way to do this?

If there IS a way to do this in the query itself then that would be my preference though.

Thanks

You can use GROUP BY and string_agg to cancat rows, somelike this:

Create table:

CREATE TABLE test
(
won int,
name character varying(255),
item character varying(255)
); 


insert into test (won, name, item) values (1,'Joe', 'A'),(1, 'Joe', 'B'),(2, 'Smith', 'A')

And do this in the query:

select won, name, string_agg(item, ',') from test group by won, name order by won

See this example in sqlFiddle

A sql approach:

SELECT won, name
      ,STRING_AGG(item, ',' ORDER BY item) AS items
  FROM myTable
  GROUP BY won, name
  ORDER BY won, name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM