Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Query rows as columns ( MySQL)

Tags:

sql

mysql

My table structure:

cust_id | action   | action_count
--------+----------+-------------
1       | Approved | 15
2       | Approved | 25
1       | Rejected | 6
2       | Pending  | 20
2       | Rejected | 7

I have to get the query result as:

cust_id | Approved | Pending | Rejected
--------+----------+---------+---------
1       | 15       | 0       | 6
2       | 25       | 20      | 7
like image 550
Sujithmon Padinhare Puthiyotti Avatar asked Jan 28 '26 01:01

Sujithmon Padinhare Puthiyotti


1 Answers

Try this query

select 
   cust_id, 
   max(if(action='Approved', action_count, 0)) as Approved,
   max(if(action='Rejected', action_count, 0)) as Rejected,
   max(if(action='Pending', action_count, 0)) as Pending
from 
   tbl
group by 
   cust_id

FIDDLE

| CUST_ID | APPROVED | REJECTED | PENDING |
-------------------------------------------
|       1 |       15 |        6 |       0 |
|       2 |       25 |        7 |      20 |
like image 196
Meherzad Avatar answered Jan 30 '26 19:01

Meherzad



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!