简体   繁体   English

如何在MySQL中将行转换为列

[英]How transform rows to column in mysql

I have this query 我有这个查询

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

It returns a table like this: 它返回如下表:

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

The code from arguments are dynamics, ex: year(d.data_recebimento) could be any year an ts.id in (245, 671, 210) coulb be any code send by the user. 参数中的代码是动态的,例如:year(d.data_recebimento)可以是(245,671,210)中的ts.id的任何年份,可以是用户发送的任何代码。 Here AAAA = 210, BBBB = 245 and C = 671. 这里AAAA = 210,BBBB = 245,C = 671。

I would like to write a query that return a table like below: 我想编写一个查询,返回一个如下表的查询:

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

Thanks. 谢谢。

You need some kind of dynamic sql. 您需要某种动态sql。

In MySql it can be done using Prepared Statements 在MySql中,可以使用预处理语句来完成


Below is a simple example 下面是一个简单的例子
- assumming that results of your query is saved into a temporary table named your_query_goes_here -假设您的查询结果已保存到名为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;

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM