Search code examples
postgresql-9.6

Is they any way to use postgresql session variable while using select statement


I have a specific request to reflect a user only once if that user has more than one policy,i need a way to left blank duplicated fields and only show real value one time like below:

CREATE OR REPLACE FUNCTION get_user_name(user_pk NUMERIC)
RETURNS text AS
$body$
DECLARE users_array NUMERIC[];
BEGIN
IF (select array_position(users_array, user_pk)) THEN
   return ' ';
ELSE
   users_array = array_append(users_array, user_pk);
   return (SELECT first_name || ' ' || last_name FROM user where id=user_pk);
END IF;
END
$body$
LANGUAGE plpgsql;

SELECT
    row_number() OVER () as id,
    get_user_name(user_pk := users.id) as client,
    policy.policy as policy,
FROM policies_policy as policy
INNER JOIN user users
order by users.id;

I need a way to not re declare users_array every time function called


Solution

  • Assuming the right hand picture is what you want, there is no need for a function:

    SELECT case when 
             row_number() OVER (partition by u.id) = 1 then concat_ws(' ', u.first_name, u.last_name)
           end as as name,
           p.policy
    FROM policies_policy as policy
      JOIN "user" u on u.id = policy.user_pk
    order by u.id;
    

    Or alternatively, simply collect all policies for each user in a comma separated list:

    SELECT u.id,
           string_agg(p.policy::text, ',') as policies
    FROM policies_policy as policy
      JOIN "user" u on u.id = policy.user_pk
    group by u.id
    order by u.id;