0

I have this type of table and I'd like to convert:

This kind of table:

customer_name   product_type    total_paid
   Lian             car            100
   Lian          motorbike         200
   Carl             car            300
   Carl          motorbike         500

In this other kind of table:

customer_name   car  motorbike
    Lian        100     200
    Carl        300     500

Using Postgresql, I would really appreciate if someone can help me please.

2 Answers 2

1

You can use a group by and the SUM aggregate function.

SELECT customer_name,
       SUM(CASE WHEN product_type='car' THEN total_paid ELSE 0 END) as car,
       SUM(CASE WHEN product_type='motorbike' THEN total_paid ELSE 0 END) as motorbike
FROM tableyoudidnotname
GROUP BY customer_name
Sign up to request clarification or add additional context in comments.

Comments

0

Try this:

select customer_name, 
(select sum(total_paid) 
from testTable
where customer_name=T.customer_name and product_type='car') as car, 
(select sum(total_paid) 
from testTable
where customer_name=T.customer_name and product_type='motorbike') as motorbike
from testTable as T
group by customer_name
order by customer_name desc

Test in DBFiddle and replace the table 'testTable' with your table name.

1 Comment

why do 3 queries when 1 will do?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.