您可以执行此操作的一种方法是使用用户定义的变量为每个事务的每个员工创建一个行号,然后您可以通过应用带有 CASE 表达式的聚合函数将数据行转换为列:
select transactionid,
max(case when row = 1 then employeeid end) employee1,
max(case when row = 2 then employeeid end) employee2,
max(case when row = 3 then employeeid end) employee3
from
(
select t.transactionid,
e.employeeid,
@row:=case when @prev = t.transactionid then @row else 0 end +1 row,
@prev:=t.transactionid
from transaction t
left join transactionemployee e
on t.transactionid = e.transactionid
cross join (select @row:=0, @prev = 0) c
order by t.transactionid, e.employeeid
) d
group by transactionid
order by transactionid;
请参阅SQL Fiddle with Demo。
如果您不想使用用户定义的变量,则可以使用类似于以下的子查询:
select transactionid,
max(case when row = 1 then employeeid end) employee1,
max(case when row = 2 then employeeid end) employee2,
max(case when row = 3 then employeeid end) employee3
from
(
select t.transactionid,
e.employeeid,
(select count(*)
from transactionemployee te
where e.transactionid = te.transactionid
and te.employeeid <= e.employeeid) row
from transaction t
left join transactionemployee e
on t.transactionid = e.transactionid
) d
group by transactionid;
请参阅带有演示的 SQL Fiddle