0
   id Event No  BrandId  
    1   10           B2            
    2   10           B8            
    3   11           B1         
    4   13           B9         
    5   13           B3    

I want the above table as a resultant from a SQL View query.

For Instance Brand Id matched are B2 and B8 for Event 10, therefore 2 records are created for it.

Just want to know how can I create records with number of brands matched.

7
  • are you storing comma separated values in columns? Commented Dec 8, 2016 at 7:31
  • Yes.... But I want the result to be as the 1st table mentioned in my question.... means a separate record for each brand id matched with an event Commented Dec 8, 2016 at 7:34
  • Storing comma separated values is a really, really bad idea. Commented Dec 8, 2016 at 7:35
  • Please post a complete example of the input data, the expected output and the definition of the tables (and views) involved. The multiple levels of unnesting aggregating and casting to an array seem overly complicated in your statement - it's hard to understand what you are trying to accomplish with that (and thus to suggest a better solution) Commented Dec 8, 2016 at 7:38
  • stackoverflow.com/questions/3653462/… Commented Dec 8, 2016 at 7:41

1 Answer 1

1

It seems like you want a simple aggregation:

SELECT "Event No", array_agg("BrandId") AS brand_array
FROM   tbl
GROUP  BY "Event No"
ORDER  BY "Event No";  -- optional

Or string_agg("BrandId", ', ') AS brand_list.
Read about aggregate functions in the manual.

Sign up to request clarification or add additional context in comments.

2 Comments

In my question the table is "Event" and the Brand Id is calculated on a sub-query. Therefore for a single event more than one brand id could be matched. Hence I need to fire my sql query on table event and make number of records to the number of brand ids matched. I don't think the solution you provided is what exactly I needed.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.