mysql将行转换为列

时间:2013-01-08 11:57:15

标签: mysql

我有一个包含两列的表:client_idinvoice_id。对于每个client id,可以有多个发票ID。我正在搜索MySQL查询,将上述表的行转换为列。我只需要每个客户的前两张发票。类似下面的伪代码:

SELECT ci.client_id, 
  first(ci.invoice_id) AS invoice_column1, 
  second(ci.invoice_id) AS invoice_column2
FROM client_invoices ci
GROUP BY ci.client_id

client_invoices的示例数据

client_id | invoice_id 
1           45
2           56
1           88

示例输出

client_id | invoice_column1 | invoice_column2
1           45                88
2           56                NULL

3 个答案:

答案 0 :(得分:1)

假设您有一个包含每个客户端多个条目的表,预期的查询应如下所示。

SELECT
    ci.client_id,
    GROUP_CONCAT(ci.invoice_id) as InvoiceIds
FROM(
    SELECT
        client_id,
        invoice_id,
        @num := if(@group = client_id, @num + 1, 1) as row_number,
        @group := client_id as dummy                
    FROM    client_invoices
    GROUP BY client_id , invoice_id
    HAVING row_number <= 2  
) as ci
GROUP BY ci.client_id 

Demo

答案 1 :(得分:0)

这样的东西?

DECLARE tmp int(11);
DECLARE tmp2 int(11);
SELECT invoice_id INTO tmp FROM ci LIMIT 1,1;
SELECT invoice_id INTO tmp2 FROM ci LIMIT 2,1;
SELECT ci.client_id, 
 tmp AS invoice_column1, 
 tmp2 AS invoice_column2
 FROM client_invoices ci
 GROUP BY ci.client_id

答案 2 :(得分:0)

您可以使用以下内容按组分配行号,然后将数据转换为列:

select client_id,
  max(case when group_row_number = 1 then invoice_id end) Invoice1,
  max(case when group_row_number = 2 then invoice_id end) Invoice2
from
(
  select client_id, invoice_id,
    @num := if(@client_id = `client_id`, @num + 1, 1) as group_row_number,
    @client_id := `client_id` as dummy, overall_row_num
  from
  (
    select client_id, invoice_id, @rn:=@rn+1 overall_row_num
    from client_invoices, (SELECT @rn:=0) r
  ) x
  order by client_id, overall_row_num
) src
group by client_id

请参阅SQL Fiddle with Demo

或者更简单的方法:

select client_id, 
  max(case when rownum = 1 then invoice_id end) Invoice1,
  max(case when rownum = 2 then invoice_id end) Invoice2 
from 
(
  select client_id,
    invoice_id,
    @row:=if(@prev=client_id,@row,0) + 1 as rownum,
    @prev:=client_id 
  from client_invoices
  order by client_id
)src
group by client_id;

请参阅SQL Fiddle with Demo

两者都产生结果:

| CLIENT_ID | INVOICE1 | INVOICE2 |
-----------------------------------
|         1 |       45 |       88 |
|         2 |       56 |   (null) |