How to obtain a sample from the same table with different conditions?


Warning: count(): Parameter must be an array or an object that implements Countable in /home/styllloz/public_html/qa-theme/donut-theme/qa-donut-layer.php on line 274
0 like 0 dislike
44 views
For example, there is a table in postgres:
|user_id | message |
|---------|----------------|
|1 | Bought A Lada |
|1 | Bought A Volvo |
|1 | Bought A Kia |
|2 | Bought A Lada |
|3 | Bought A Kia |
|3 | Bought A Kia |
Car can only be 3: Lada , Volvo, Kia. Tell me how to write a query to answer was this:
|user_id| Lada | Volvo | Kia |
| 1 | 1 | 1 | 1 |
| 2 | 1 | 0 | 0 |
| 3 | 0 | 0 | 2 |
by | 44 views

1 Answer

0 like 0 dislike
SELECT user_id, SUM(CASE WHEN (message='I Bought a Lada') THEN 1 ELSE 0 END) AS Lada, SUM(CASE WHEN (message='I Bought a Volvo') THEN 1 ELSE 0 END) AS Volvo, SUM(CASE WHEN (message='I Bought a Kia') THEN 1 ELSE 0 END) AS Kia FROM your_table GROUP BY user_id
by

Related questions

0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
110,608 questions
257,186 answers
0 comments
38,662 users