如何在mysql中将行转换为列

时间:2014-12-22 18:47:48

标签: mysql pivot group-concat crosstab

我有这个查询

select  ts.nome,
        year(d.data_recebimento) as ano,
        count(*) as qtd
from    documento d inner join documento_tipo_solicitacao dts on (d.id = dts.documento_id)
                    inner join tipo_solicitacao ts on (dts.tipo_solicitacao_id = ts.id)
where   year(d.data_recebimento) in (2008, 2010)
and     ts.id in (245, 671, 210)
group by ts.nome, 
         year(d.data_recebimento)
order by 1, 2

它返回一个这样的表:

|---------|---------|------|
|nome     |ano      |qtd   |
|---------|---------|------|
|AAAA     |2008     |10    |
|AAAA     |2010     |15    |
|BBBB     |2008     |20    |
|CCCC     |2008     |12    |
|CCCC     |2010     |13    |
|---------|---------|------|

来自参数的代码是动态的,例如:年(d.data_recebimento)可以是任何年份,(245,671,210)中的ts.id可以是用户发送的任何代码。这里AAAA = 210,BBBB = 245,C = 671。

我想编写一个返回如下表格的查询:

|---------|---------|------|
|nome     |2008     |2010  |
|---------|---------|------|
|AAAA     |10       |15    |
|BBBB     |20       |0     | --> BBBB on 2010 could be blank.
|CCCC     |12       |13    |
|---------|---------|------|

感谢。

1 个答案:

答案 0 :(得分:1)

你需要某种动态的sql
在MySql中,可以使用Prepared Statements

完成


下面是一个简单的示例
- 假设您的查询结果保存到名为your_query_goes_here

的临时表中
SET @sql = (
     SELECT concat( 'SELECT `nome`, ',
       ( SELECT group_concat( DISTINCT
            concat('min(if( `ano`=', ano, 
                   ',`qtd`,null)) AS col_',`ano`) )
         FROM your_query_goes_here
       ),
       ' FROM your_query_goes_here GROUP BY `nome`')
)
;

SELECT @sql;

PREPARE stmt1 FROM @sql;
EXECUTE stmt1;

演示:http://sqlfiddle.com/#!9/77696/3