[GENERAL] sub-select with multiple records, columns - Mailing list pgsql-general

From Israel Brewster
Subject [GENERAL] sub-select with multiple records, columns
Date
Msg-id 34A99D9B-819D-404A-BABB-AF0CC29AF351@ravnalaska.net
Whole thread Raw
Responses Re: [GENERAL] sub-select with multiple records, columns
List pgsql-general
I have two tables, a ticket table and a notes table, set up where each ticket can have multiple notes. I'm trying to come up with a query that returns the ticket fields as well as a field that is an array type field with the values being json-encoded note records. I've come up with the following subselect query, which works:

SELECT
...
(SELECT 
array_agg(to_json(row(notedate,username,note))) 
FROM sabrenotes 
INNER JOIN users ON author=users.id 
WHERE ticket=sabretickets.id ) notes
FROM tickets
WHERE ...

The only problem with this query is that the notes aren't sorted. Of course, simply adding an ORDER BY clause to the sub-select doesn't work - it throws an error about needing to use notedate in a GROUP BY clause or aggregate function. Is there some way I can get sorting as well here? Of course, I could just run a second query to get the notes, and combine in code, but that's no fun... :-)
-----------------------------------------------
Israel Brewster
Systems Analyst II
Ravn Alaska
5245 Airport Industrial Rd
Fairbanks, AK 99709
(907) 450-7293
-----------------------------------------------



Attachment

pgsql-general by date:

Previous
From: Dmitry O Litvintsev
Date:
Subject: Re: [GENERAL] autovacuum holds exclusive lock on table preventing itfrom to be updated
Next
From: Thomas Kellerer
Date:
Subject: Re: [GENERAL] sub-select with multiple records, columns