4

a rookie MYSQL user .... I have a simple MySQL query that returns values, and uses the GROUP_CONCAT function:

SELECT Productid, Name, GROUP_CONCAT(value)
FROM search_export 
Group By Productid, Name;

Productid   Name                     GROUP_CONCAT(value)
666056542   Brand Name           Netgear
1054677552  Ethernet Technology  Gigabit Ethernet
665655662   Form Factor          Wall Mountable,Desktop
56565765    Media Type Supported     Twisted Pair

However, I need to transpose the query so it returns 'Name' as seperate columns, not a row. Is this possible at all with MySQL?

Marc
  • 537
  • 2
  • 7
  • 19
  • Hi,Yes, multiple records with different names - I need each 'Name' row as a column, so for e.g. Brand Name | Ethernet Technology | Form Factor | Media Type Supported – Marc Nov 27 '12 at 10:04

1 Answers1

10

You need to perform a PIVOT operation, which is not supported natively in MySQL (unlike some other RDBMS).

The closest you can get is to construct SQL along the following lines:

SELECT   ProductId,
         GROUP_CONCAT(IF(Name='Brand Name'          ,value,NULL))
           AS `Brand Name`,
         GROUP_CONCAT(IF(Name='Ethernet Technology' ,value,NULL))
           AS `Ethernet Technology`,
         GROUP_CONCAT(IF(Name='Form Factor'         ,value,NULL))
           AS `Form Factor`,
         GROUP_CONCAT(IF(Name='Media Type Supported',value,NULL))
           AS `Media Type Supported`
FROM     search_export
GROUP BY ProductId

If the possible Name values are dynamic, you could generate such SQL in a higher level language from the results of:

SELECT DISTINCT Name FROM search_export

Indeed, one could even use SQL itself:

SELECT CONCAT('
         SELECT   ProductId, ',
       GROUP_CONCAT('
                  GROUP_CONCAT(IF(Name=',QUOTE(Name),',value,NULL))
                    AS `',REPLACE(Name,'`','``'),'`'
       ), '
         FROM     search_export
         GROUP BY ProductId
       ')
INTO @sql
FROM (
  SELECT DISTINCT Name FROM search_export
) t;

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

Note that if there are a lot of different Name values, you may need to increase group_concat_max_len from its default of 1KiB.

eggyal
  • 122,705
  • 18
  • 212
  • 237