我有一个这样的表:
Trans Time_In Placard Container Sztp Line Time_Out
===== ======= ======= ========= ==== ==== ========
IN 10:15 254114 CLHU12345 40DH MAE 10:54 <In transaction
OUT 10:15 254114 MAEU45678 20DR SEA 10:54 <Out Transaction (same placard)
OUT 10:15 254114 TTNU98765 20DR CHI 10:54 <Out Transaction (same placard)
IN 11:23 664524 FSCU13479 40RH SEB 11:55 <In transaction
OUT 11:23 664524 PONU55588 40DR MAB 11:55 <Out Transaction (same placard)
IN 13:01 542234 TLHU77665 40RH MOL 13:23 <In transaction (no out)
OUT 13:36 232212 MLHU22341 20DR CMD 13:49 <Out Transaction (no in)
OUT 14:03 187852 AMFU56041 20DR CMD 14:48 <Out Transaction (no in)
OUT 14:03 187852 CCLU44112 20DR CHN 14:48 <Out Transaction, same placard (no in)
是一排卡车,它们进入航站楼转换容器,有时会挑选一辆 40 英寸或两辆 20 英寸的卡车驶出。有时,卡车司机只是扔下一个容器然后空着走,所以没有 OUT 交易。或者,如果他选择一个 40 或两个 20,则可能会空出一个满的容器,因此没有 IN 交易,而只有一两个 OUT。每个标语牌的入时和超时都是相同的,因此我可以从任何记录中获取它,所以不用担心。
关键是Time_In + 标牌,因为同一张标牌可以进行多次进出。每次行程的时间戳完全相同。
我需要得到这样的结果:
Trans Time In Placard Cont1 Sztp1 Line1 Cont2 Sztp2 Line2 Cont3 Sztp3 Line3 Time Out
===== ======= ======= ========= ===== ===== ========= ===== ===== ========= ===== ===== ========
IN 10:15 254114 CLHU12345 40DH MAE MAEU45678 20DR SEA TTNU98765 20DR CHI 10:54
IN 11:23 664524 FSCU13479 40RH SEB PONU55588 40DR MAB null null null 11:55
IN 13:01 542234 TLHU77665 40RH MOL null null null null null null 13:23
OUT 13:36 232212 MLHU22341 20DR CMD null null null null null null 13:49
OUT 14:03 187852 AMFU56041 20DR CMD CCLU44112 20DR CHN null null null 14:48
感谢您的帮助。
更新:刚刚重写了整个问题,因为它不够清楚。另外标题也错了,不是多个字段转为行,而是相反:多个行转为字段。对此感到抱歉。
最佳答案
我认为 MySQL 存储过程或您的编程语言中的一次游标操作可能会更有效。将所有这些复杂关系合并到一个查询中对于实现、审查或维护来说并不容易。
这是使用临时表构建和保存结果的另一种解决方案,其中 t1 是原始数据表,t3 是结果表。
drop table if exists t3;
create temporary table t3 (placecard int, Trans varchar(10), TimeIn varchar(10), ContIn varchar(20), InSize varchar(10), InLine varchar(10), ContOut1 varchar(20),
ContSize1 Varchar(10), ContLine1 varchar(10), ContOut2 varchar(20), ContSize2 varchar(10), ContLine2 Varchar(10), TimeOut varchar(10) );
insert into t3
(placecard, timein, timeout)
select placecard, min(timein), max(timeout) from t1
group by placecard;
update t3
join t1
on t3.placecard = t1.placecard and t3.timein = t1.timein and t1.transaction='IN'
set trans ='IN', contin = t1.Container, InSize = t1.Size, InLine = t1.Line
where t3.placecard>0;
update t3
join t1
on t3.placecard= t1.placecard and t1.transaction='OUT'
set contOut1 = t1.Container , ContLine1 = t1.line , ContSize1 = t1.size
where t3.placecard>0;
update t3
join t1
on t3.placecard= t1.placecard and t1.transaction='OUT' and t3.contOut1 <> t1.Container
set contOut2 = t1.Container , ContLine2 = t1.line , ContSize2 = t1.size
where t3.placecard>0 ;
select * from t3;
您可以将其构建到存储过程中并添加参数来限制范围。
或者您可以将其构建到更新计划表的计划作业中。
关于MySQL 在字段中跨越多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30742478/