我需要在mysql中使用第一列中的重复值和第2列中的唯一值来转置数据

时间:2016-05-25 11:12:07

标签: mysql

使用以下信息表:

id | job | code
1  | 100 | ab123
2  | 100 | ab124
3  | 101 | ab125
4  | 101 | ab126
5  | 101 | ab127
6  | 102 | ab128
7  | 102 | ab129
8  | 103 | ab130
9  | 104 | ab131

我需要让下表在其他查询中使用3个代码:

job | code1 | code2 | Code3
100 | ab123 | ab124 |
101 | ab125 | ab126 | ab127
102 | ab128 | ab129 |
103 | ab130 |       |
104 | ab131 |       |

只会有3个代码。

提前致谢

1 个答案:

答案 0 :(得分:3)

这对于MySQL来说有点棘手(与具有窗口和透视功能的其他数据库相比),但是您可以通过使用查询将每组作业项中的行编号为派生表并将其用作源来实现此目的对于带有条件聚合的外部查询:

select 
  job,
  max(case when rn = 1 then code end) as Code1,
  max(case when rn = 2 then code end) as Code2,
  max(case when rn = 3 then code end) as Code3
from (
  select id,     
       code,
       case job 
           when @grp then @row := @row + 1 
           else @row := 1
       end as rn,
       @grp := job as job
  from Table1 t
  join (select @row := 0, @grp := '') r
  order by id, job
) s
group by job

我假设代码项应按ID排序,但如果你想通过代码,只需更改派生表中的order by子句。

编号部分基于this question的答案。

Sample SQL Fiddle

示例输出:

| job | Code1 |  Code2 |  Code3 |
|-----|-------|--------|--------|
| 100 | ab123 |  ab124 | (null) |
| 101 | ab125 |  ab126 |  ab127 |
| 102 | ab128 |  ab129 | (null) |
| 103 | ab130 | (null) | (null) |
| 104 | ab131 | (null) | (null) |