1

在一些业务应用程序中,原始数据进来,我对其进行规范化和处理,并将它们存储以用于报告目的。

例如,原始数据:

Transaction (transaction ID, employee 1 ID, employee 2 ID, employee 3 ID)

归一化为

Transaction(transaction ID)

TransactionEmployee (transaction ID, employee ID)

当谈到报告要求时,员工必须排成一排 - 比如TransactionReport(transaction ID, some details, employee 1 ID, employee 2 ID, employee 3 ID)

我的解决方案是使用应用程序编程语言循环 TransactionEmployee,并构造 INSERT 语句以将报告数据放入另一个表中 - 每个事务都有 3 个员工 ID。

但我会觉得用 SQL 来做会更舒服。

这通过 SQL 可行吗?

4

1 回答 1

0

您可以执行此操作的一种方法是使用用户定义的变量为每个事务的每个员工创建一个行号,然后您可以通过应用带有 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

于 2013-08-07T01:04:31.073 回答