Domanda

I have below database table:

id       Creation_Date         Goals  Alternative    Value
-----------------------------------------------------------
1   2014-04-17 10:09:30         G1         A         0.86
2   2014-04-17 10:09:30         G1         B         0.87
3   2014-04-17 10:09:30         G2         A         0.5
4   2014-04-17 10:09:30         G2         B         0

I am firing below query:

  select 
    alternative,
    max( case when goals='G1' then round( value, 2 ) end ) as 'G1',
    max( case when goals='G2' then round( value, 2 ) end ) as 'G2'
    from sgwebdb.dim_module
  group by alternative
  ;

and getting below output:

 Alternative    G1       G2
-----------------------------
 A            0.86      0.50    
 B            0.87      0.00

Now Goals are not pre defined (G1, G2, G3, G4, ...), it can be any number. Can I have a query so that I get the same output without defining a number of goals in the query?

È stato utile?

Soluzione

Something like this might work:

SET @sql = NULL;
SELECT
  GROUP_CONCAT(DISTINCT
    CONCAT(
      'MAX(IF(goals = ''',
      goals,
      ''', round(value, 2), NULL)) AS ',
      goals
    )
  ) INTO @sql
FROM sgwebdb.dim_module;
SET @sql = CONCAT('SELECT alternative, ', @sql, ' FROM sgwebdb.dim_module GROUP BY alternative');

prepare stmt from @sql;
execute stmt;

Source: http://buysql.com/mysql/14-how-to-automate-pivot-tables.html

SQL Fiddle: http://sqlfiddle.com/#!2/ac9f88/10

Altri suggerimenti

Pivot is what you are looking for, but is apparently not supported in MySQL. Attached another article that shows how it can be (sortof) done:

http://stratosprovatopoulos.com/web-development/mysql/pivot-table-with-dynamic-columns/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top