I have two columns A and B, and would like to get a list of items(and their counts) in column B grouped by items in column A, and create a new table with the information. So the new table will look something like:
newCol1 | newCol2
--------+--------
a1, | b1:3,b4:1,b7:11
a2, | b2:1,b3:5,b4:3,b8:2
…and so forth. (delimiters can be anything, though. If concatenating item and count is not possible, I could also have one column with a list of items and another column with a list of counts separated by a delimiter.)
I can do this in Java by first getting all the items and storing them in a map with count updates, and then update the new table, but I was wondering if there’s any way to do this in PostgreSQL (perhaps by writing a function).
I’ve looked at array function in PostgreSQL but didn’t get far. Any pointers as well as suggestions for storing such data would be appreciated.
aandbare of typetext, I assume.Or use
string_agg()as @a_horse demonstrates to get a string instead of an array as result.