在MYSQL中选择行作为列

时间:2012-11-29 14:26:12

标签: mysql sql pivot

您好我想弄清楚如何做到这一点我有一个mysql表

| ID |    ACC_ID  | line_id | code     |
| 1  |          1 |    5960 | DCA      |
| 2  |          1 |    5960 | AAA      |
| 3  |          1 |    5960 | DDD      | 
| 4  |          1 |    5960 | DER      |
| 5  |          1 |    5054 | DCB      |
| 6  |          1 |    5054 | AAC      |
| 7  |          1 |    5011 | DDE      |
| 8  |          1 |    5012 | DEQ      |

等数据库下降大约10000行

我想创建一个将执行此操作的mysql select语句

| ACC_ID     | line_id | code     | code     | code     | code     | 
|   1        | 5960    | DCA      | AAA      | DDD      | DER      | 
|   1        | 5054    | DCB      | DER      |          |          |
|   1        | 5011    | DDE      |          |          |          |
|   1        | 5012    | DEQ      |          |          |          |
每个line_id最多可以有十个代码

现在我的问题是可以使用select语句进行上面的查询。

谢谢大家的帮助

1 个答案:

答案 0 :(得分:3)

这是PIVOT,但MySQL没有PIVOT函数,但您可以使用聚合函数和CASE语句复制它。 MySQL也没有最简单的方法来按组分配行号,但以下是如何使用SQL实现此目的的示例。由于您说每line_id最多可以有10个代码,因此我对可能的解决方案进行了硬编码。

select acc_id,
  line_id,
  max(case when group_row_number = 1 then code end) Code1,
  max(case when group_row_number = 2 then code end) Code2,
  max(case when group_row_number = 3 then code end) Code3,
  max(case when group_row_number = 4 then code end) Code4,
  max(case when group_row_number = 5 then code end) Code5,
  max(case when group_row_number = 6 then code end) Code6,
  max(case when group_row_number = 7 then code end) Code7,
  max(case when group_row_number = 8 then code end) Code8,
  max(case when group_row_number = 9 then code end) Code9,
  max(case when group_row_number = 10 then code end) Code10
from
(
  select ACC_ID,
    line_id,
    code, 
    @num := if(@ACC_ID = `ACC_ID` AND @line_id = `line_id`, @num + 1, 1) as group_row_number,
    @ACC_ID := `ACC_ID` as dummy,
    @line_id := `line_id` as linedummy
  from yourtable
) src
group by acc_id, line_id
order by line_id desc

请参阅SQL Fiddle with Demo

结果:

| ACC_ID | LINE_ID | CODE1 |  CODE2 |  CODE3 |  CODE4 |  CODE5 |  CODE6 |  CODE7 |  CODE8 |  CODE9 | CODE10 |
-------------------------------------------------------------------------------------------------------------
|      1 |    5960 |   DCA |    AAA |    DDD |    DER | (null) | (null) | (null) | (null) | (null) | (null) |
|      1 |    5054 |   DCB |    AAC | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) |
|      1 |    5012 |   DEQ | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) |
|      1 |    5011 |   DDE | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) | (null) |