我有以下数据库表:
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,...),它可以是任何数字。我是否可以查询,以便在不在查询中定义多个目标的情况下获得相同的输出?
答案 0 :(得分:0)
Pivot正是您所寻找的,但显然在MySQL中不受支持。附上另一篇文章,展示如何(sortof)完成:
http://stratosprovatopoulos.com/web-development/mysql/pivot-table-with-dynamic-columns/
答案 1 :(得分:0)
这样的事可能有用:
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