数据库行需要包含列

时间:2014-04-17 04:08:55

标签: mysql

我有一个下面的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

2 个答案:

答案 0 :(得分:1)

尝试此查询:

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 to 1G2 to 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

答案 1 :(得分:0)

OP的评论

  

我尝试了下面的查询,但它给了我重复的列

     

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分组才能goals根据alternative转换为列

查询

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 |
+-------------+------+------+