Following tables:
CREATE TEMPORARY TABLE guys ( guy_id integer primary key, guy text ); CREATE TEMPORARY TABLE sales ( log_date date, sales_guys integer[], sales smallint ); INSERT INTO guys VALUES(1,'john'),(2,'joe'); INSERT INTO sales VALUES('2016-01-01', '{1,2}', 2),('2016-01-02','{1,2}',4); Following query works great to show names on a given date:
SELECT log_date, sales_guys, ARRAY_AGG(guy), sales FROM sales JOIN guys ON guys.guy_id = ANY(sales.sales_guys) GROUP BY log_date, sales_guys, sales ORDER BY log_date ASC; log_date | sales_guys | array_agg | sales ------------+------------+------------+------- 2016-01-01 | {1,2} | {john,joe} | 2 2016-01-02 | {1,2} | {john,joe} | 4 Following query problematically gives me a name per date per guy, so here each name twice, and so on):
SELECT sales_guys, ARRAY_AGG(guy), SUM(sales) AS sales FROM sales JOIN guys ON guys.guy_id = ANY(sales.sales_guys) GROUP BY sales_guys; Yields:
sales_guys | array_agg | sales ------------+---------------------+------- {1,2} | {john,joe,john,joe} | 12 Is there a way to somehow reduce the ARRAY_AGG call to give only the unique names?
{1,2}with{2,1}? And always declare your version of Postgres.