S
S
superkolya2019-01-30 20:49:12
PostgreSQL
superkolya, 2019-01-30 20:49:12

How to get a selection from the same table for different conditions?

For example, there is a table in postgres:
|user_id | message |
|---------|----------------|
|1 | Bought Lada |
|1 | Bought Volvo |
|1 | Bought Kia |
|2 | Bought Lada |
|3 | Bought Kia |
|3 | Bought Kia |
There can be only 3 car brands: Lada, Volvo, Kia. Tell me how to make a request so that the answer is:
|user_id| Lada | Volvo | Kia |
| 1 | 1 | 1 | 1 |
| 2 | 1 | 0 | 0 |
| 3 | 0 | 0 | 2 |

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
nozzy, 2019-01-30
@superkolya

SELECT
    user_id,  
    SUM(CASE WHEN (message='Купил Lada') THEN 1 ELSE 0 END) AS Lada,
    SUM(CASE WHEN (message='Купил Volvo') THEN 1 ELSE 0 END) AS Volvo,
    SUM(CASE WHEN (message='Купил Kia') THEN 1 ELSE 0 END) AS Kia
FROM 
    your_table
GROUP BY 
    user_id

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question