Search code examples
sqlpostgresqltranspose

How to unite several tables in a one so the names of the columns became the row names?


for instance I have

SELECT customer_id, first_name || ', ' || last_name || ', ' || email as "customer's info" 
FROM customer
WHERE customer_id = 5
;

SELECT count(i.film_id) AS "num.of films rented" FROM payment p
JOIN rental r ON p.rental_id = r.rental_id
JOIN inventory i ON r.inventory_id = i.inventory_id
WHERE r.rental_date >= ('2014-01-01'::date)
AND r.rental_date <= ('2017-05-03'::date)
AND p.customer_id = 5
;

I want in output

metric1              | metric2 
----------------------------
customer's info      | blalalalal
num.of films rented  | blalalalal

I try smth like, but nothing

SELECT * FROM crosstab(
SELECT first_name || ', ' || last_name || ', ' || email
FROM customer WHERE customer_id = 5,
SELECT count(i.film_id) FROM payment p
JOIN rental r ON p.rental_id = r.rental_id
JOIN inventory i ON r.inventory_id = i.inventory_id
WHERE r.rental_date >= ('2014-01-01'::date) 
AND r.rental_date <= ('2017-05-03'::date)) 
AS ('fjfjf' TEXT, 'fjfjf' int );

Could you help me? I dont know how to do it in postgress Thanks a lot


Solution

  • I would UNION ALL the two queries together - but remember to CAST the count value as a string, as you need matching data types to UNION:

    SELECT 
      'customer''s info'                               AS "name"
    , first_name || ', ' || last_name || ', ' || email AS "value" 
    FROM customer c
    UNION ALL
      'num.of films rented'         AS "name"
    , COUNT(i.film_id)::VARCHAR(5)  AS "value"
    FROM payment p 
    JOIN rental r ON p.rental_id = r.rental_id
    JOIN inventory i ON r.inventory_id = i.inventory_id
    WHERE r.rental_date >= ('2014-01-01'::date)
    AND r.rental_date <= ('2017-05-03'::date)
    WHERE customer_id = 5
    ;