Row to column transformation in MySQL

后端 未结 2 2071
庸人自扰
庸人自扰 2020-12-20 00:41

I have this result set in MySQL :

ID          Type Email          Degignation  
1000000000  202 brijesh@abc.com Entrepreneur
1000000000  234 brijesh@abc.com          


        
2条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-20 01:06

    This is called a pivot table. It's kind of awkward to produce:

    SELECT ID, 
     MAX(CASE Type WHEN 202 THEN Degignation END) AS `202`
     MAX(CASE Type WHEN 234 THEN Degignation END) AS `234`
     MAX(CASE Type WHEN 239 THEN Degignation END) AS `239`
     Email
    FROM mytable
    GROUP BY ID, Email
    

    Note that you must know all the distinct Type values before you write the query. SQL doesn't allow a result set to add more columns dynamically as it discovers data values in the table. Columns must be fixed at query prepare time.

提交回复
热议问题