Mysql
 SQL >> Database >  >> RDS >> Mysql

Riorganizzare una tabella MySQL facendo perno sui valori delle righe

Si tratta in sostanza di un'operazione PIVOT; poiché però MySQL non ha una funzione PIVOT integrata, la replichi con una funzione di aggregazione e un'espressione CASE. Se sai già quanti valori distinti di Grant esistono, puoi scrivere la query in modo statico così:

select Month, sum(case when `grant`='DOE' then subtotal else 0 end) DOE, sum(case when `grant`='Hatch' then subtotal else 0 end) Hatch, sum(case when `grant`='NIH' then subtotal else 0 end) NIH, sum(case when `grant`='NSF' then subtotal else 0 end) NSF, sum(case when `grant`='Other' then subtotal else 0 end) Other, sum(case when `grant`='State' then subtotal else 0 end) State from yourtable group by month 

Guarda la demo su SQL Fiddle

Se il numero di valori di Grant non è noto, puoi costruire la query dinamicamente con uno statement preparato:

SET @sql = NULL; SELECT GROUP_CONCAT(DISTINCT CONCAT( 'sum(case when `Grant` = ''', `Grant`, ''' then Subtotal else 0 end) AS `', `Grant`, '`' ) ) INTO @sql FROM yourtable; SET @sql = CONCAT('SELECT month, ', @sql, ' FROM yourtable group by month'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; 

Guarda la demo su SQL Fiddle

Entrambi gli approcci producono lo stesso risultato:

| MONTH | HATCH | NIH | NSF | OTHER | DOE | STATE | ----------------------------------------------------------------- | Nov-2012 | 144.56 | 240.9 | 100.7 | 276.67 | 0 | 0 | | Oct-2012 | 321.54 | 0 | 234.53 | 312.35 | 214.35 | 0 | | Sep-2012 | 147.99 | 0 | 156.89 | 245.67 | 0 | 148.66 |