Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to select Column value as Column name with conditions in SQL table

Tags:

sql

mysql

I'm new to SQL. I have a table 'Customers' and it looks like this.

enter image description here

I would like to select 'Gender' AS Gender Column and 'Age' as Age column which would be like this.

enter image description here

I've tried several ways but it still doesn't show what I need. Please help me.

like image 335
Den Avatar asked Oct 24 '25 04:10

Den


1 Answers

One way to go about it is to use conditional aggregation

SELECT name,
       MAX(CASE WHEN field = 'Gender' THEN value END) gender,
       MAX(CASE WHEN field = 'Age' THEN value END) age
  FROM customers
 GROUP BY name

The other way (if you're interested only in these two columns) would be

SELECT c1.name, c1.value gender, c2.value age
  FROM customers c1 JOIN customers c2
    ON c1.name = c2.name
   AND c1.field = 'Gender'
   AND c2.field = 'Age';

Assumption is that both Gender and Age exist for each Name. It it's not the case then use an OUTER JOIN instead of an INNER JOIN like so

SELECT n.name, c1.value gender, c2.value age
  FROM
(
  SELECT DISTINCT name
    FROM customers
) n LEFT JOIN customers c1
    ON n.name = c1.name AND c1.field = 'Gender' 
    LEFT JOIN customers c2
    ON n.name = c2.name AND c2.field = 'Age';

Output:

|   NAME | GENDER | AGE |
|--------|--------|-----|
| Angela | Female |  28 |
|  Davis |   Male |  30 |

Here is SQLFiddle demo

like image 171
peterm Avatar answered Oct 25 '25 19:10

peterm



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!