Return master and master details record(s) in a single row in postgresql I am trying to formulate a PostgreSQL query where I wanted to return all the payment table data in an array and customer data as a header in a single row. 
I am writing the following query to get data in a single row, but somehow I am getting several rows with the same repetitive data. I want a single data row to be returned for the requested id. I don't want to use the "limit=1" keyword to return a single row.

WITH t as (select row_to_json(rr)::jsonb as record
from (
       select (
                select row_to_json(row)
                from (
                       select 
                             c.customer_id,
                             c.first_name,
                             c.last_name,
                             c.email,                   
                             count(*) total, 
                             sum(p2.amount) total_amount
                       from payment p2
                       where p2.customer_id = c.customer_id
                     ) row
              ) as header,
              (select array_to_json(array_agg(row_to_json(row)))
                from (
                       select
                             amount,
                             payment_date                              
                       from payment p1                            
                       where p1.customer_id = c.customer_id
                     ) row
              ) as details
       from customer c
       join payment p on p.customer_id = c.customer_id
     ) rr) 

    SELECT record FROM t 
    where record-&gt;'header'-&gt;&gt;'customer_id'= '2'
It's really hard to tell what exactly you want, but maybe something like this:

select jsonb_build_object('customer', to_jsonb(c), 
                          'total_amount', pd.total_amount,
                          'payment_details', pd.payments)
from customer c
  join lateral (
     select jsonb_agg(jsonb_build_object('amount', amount, 'date', payment_date)) as payments,
            sum(amount) as total_amount
     from payment p
     where p.customer_id = c.customer_id
  ) pd on true