我有下面的数据库表:
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
我正在触发以下查询:
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
;
并获得以下输出:
Alternative G1 G2
-----------------------------
A 0.86 0.50
B 0.87 0.00
现在没有预先定义目标(G1、G2、G3、G4……),它可以是任何数字。我可以有一个查询,以便在不在查询中定义多个目标的情况下获得相同的输出吗?
最佳答案
这样的事情可能会起作用:
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;
来源:http://buysql.com/mysql/14-how-to-automate-pivot-tables.html
SQL fiddle :http://sqlfiddle.com/#!2/ac9f88/10
关于mysql - 数据库行需要显示在列中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23381716/