我有一个下面的 MySQL 表。
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
我需要一个 MySQL 查询来更改列中的行,并且还需要它们各自的值,如下所示。
**输出要求**
Alternative G1 G2
-------------------------------
A 0.86 0.50
B 0.87 0
尝试过的解决方案:
我尝试了以下查询
select Alternative , max(case when Goals = 'G1' then round(value,2) end) as Goal1, max(case when Goals = 'G2' then round(value,2) end) as Goal2 from sgwebdb.dim_module group by id ;
但这没有给出所需的输出,这给出了以下输出
Alternative G1 G2
-------------------------------
A 0.86 Null
B 0.87 Null
A Null 0.50
B Null 0.00
最佳答案
尝试这个查询:
SELECT Alternative,
SUM(Val*(1-ABS(SIGN(Goals-1)))) AS G1,
SUM(Val*(1-ABS(SIGN(Goals-2)))) AS G2
FROM table1
GROUP BY Alternative;
表格如下所示:将G1更改为1
并将G2更改为2
id Creation_Date Goals Alternative Value
-----------------------------------------------------------
1 2014-04-17 10:09:30 1 A 0.86
2 2014-04-17 10:09:30 1 B 0.87
3 2014-04-17 10:09:30 2 A 0.5
4 2014-04-17 10:09:30 2 B 0
结果如下:
Alternative G1 G2
-------------------------------
A 0.86 0.50
B 0.87 0
关于mysql - 数据库行需要包含列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23124436/