交叉表/枢轴表和缺少应为null

时间:2016-02-03 08:48:07

标签: mysql

datetime               tran_value        name
2016-01-01 10:00:00      2000               x
2016-01-01 10:00:00      3000               y
2016-01-01 11:00:00      4000               z
2016-01-02 13:00:00      5000               x
2016-01-02 13:00:00      6000               z
2016-01-03 14:00:00      7000               y

是否可以获得如下所示的输出

datetime                    x          y           z
2016-01-01 10:00:00       2000        3000        null
2016-01-01 11:00:00       null        null        4000
2016-01-02 13:00:00       5000        null        6000
2016-01-03 14:00:00       null        7000        null

提前致谢

2 个答案:

答案 0 :(得分:1)

如果你知道表格中的名字数量,那么

<强>查询

select `datetime`, 
max(case when name = 'x' then tran_value else null end) as x,
max(case when name = 'y' then tran_value else null end) as y,
max(case when name = 'z' then tran_value else null end) as z 
from tblTransactions 
group by `datetime`;

如果没有,那么你必须使用动态SQL查询。

<强>查询

set @query = null;

select
group_concat(distinct
    concat(
      'max(case when name = ''',
      name, ''' then tran_value else null end) as ',name
    )
  ) into @query
from tblTransactions ;

set @query = concat('select `datetime`, ', @query, ' from tblTransactions 
              group by `datetime`
');

prepare stmt from @query;
execute stmt;
deallocate prepare stmt;

<强>结果

+---------------------+------+------+------+
| datetime            | x    | y    | z    |
+---------------------+------+------+------+
| 2016-01-01 10:00:00 | 2000 | 3000 | NULL |
| 2016-01-01 11:00:00 | NULL | NULL | 4000 |
| 2016-01-02 13:00:00 | 5000 | NULL | 6000 |
| 2016-01-03 14:00:00 | NULL | 7000 | NULL |
+---------------------+------+------+------+

SQL Fiddle demo

答案 1 :(得分:0)

假设表名为table1

select `datetime`, 
        max(if(name='x',tran_value,null)) as x,
        max(if(name='y',tran_value,null)) as y,
        max(if(name='z',tran_value,null)) as z
 from table1 group by `datetime`

SQL小提琴:http://sqlfiddle.com/#!9/54577/1

相关问题