-1

我有一个有两列的表: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
4

3 回答 3

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 

演示

于 2013-01-08T12:08:33.317 回答
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

或者更简单的方法:

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

两者都产生结果:

| CLIENT_ID | INVOICE1 | INVOICE2 |
-----------------------------------
|         1 |       45 |       88 |
|         2 |       56 |   (null) |
于 2013-01-08T13:36:41.753 回答
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
于 2013-01-08T12:12:26.377 回答