sql—提取两个时间戳之间的分钟数并分配不同的权重

vaqhlq81  于 2021-07-29  发布在  Java
关注(0)|答案(2)|浏览(453)

我对如何在teradata中实现这一点非常头疼。
我有两个表,需要从run表中提取分钟数,并根据weights表为它们分配小时权重。
表1:运行

Machine     Begin               End
A           1/1/2010 08:00 AM   1/1/2010 10:45 AM
B           1/2/2010 10:00 AM   1/2/2010 11:45 AM

表2:重量
每小时分配一次体重(记录1显示在上午8点到9点之间每跑一分钟体重为10)

Hour                Weight  
1/1/2010 08:00 AM   10
1/1/2010 09:00 AM   15
1/1/2010 10:00 AM   16
1/1/2010 11:00 AM   20
1/1/2010 11:00 AM   20
1/1/2010 12:00 AM   25

需要的结果:

Mach    Hour                Weight  Mins    Total (Weight*Mins)
A       1/1/2010 08:00 AM   10      60      600
A       1/1/2010 09:00 AM   15      60      900
A       1/1/2010 10:00 AM   16      45      720
B       1/2/2010 10:00 AM   16      60      960
B       1/2/2010 11:00 AM   20      45      900

感谢您的指导。提前谢谢。
编辑:以下是示例表

CREATE TABLE RUNS(NAME VARCHAR(50),START_DT timestamp(0),END_dt timestamp(0));
INSERT INTO RUNS VALUES      ('A','2020-01-01 08:00:00','2020-01-01 10:15:00');
INSERT INTO RUNS VALUES      ('B','2020-01-02 10:00:00','2020-01-02 11:45:00');

CREATE TABLE WEIGHTS(HOUR_MS timestamp(0),WEIGHT INTEGER);
INSERT INTO  WEIGHTS('2020-01-01 08:00:00', 10); 
INSERT INTO  WEIGHTS('2020-01-01 09:00:00', 15);
INSERT INTO  WEIGHTS('2020-01-01 10:00:00', 16);
INSERT INTO  WEIGHTS('2020-01-01 11:00:00', 20);
INSERT INTO  WEIGHTS('2020-01-02 10:00:00', 20);
INSERT INTO  WEIGHTS('2020-01-02 11:00:00', 25);
jfewjypa

jfewjypa1#

这是一种使用基于重叠的非等连接的暴力方法:

select 
   machine
  ,weight 
   -- get the number of minutes within the hour
  ,cast((interval(period(begin, end) p_intersect period(hour, hour + interval '1' hour)) minute(4)) as int) as mins
  ,mins * weight
from run join weights 
on period(begin, end) overlaps period(hour, hour + interval '1' hour)

explain将显示一个product join,它会导致高cpu使用率。有一种更聪明的方法是使用expand-on,但对我来说太晚了,也许明天:-)

l3zydbqr

l3zydbqr2#

另一种方法是在子查询中使用expand on,然后使用equality join:

SELECT machine
  ,TheHour
  ,weight
  ,CAST((INTERVAL(pd P_INTERSECT xpd) MINUTE(4)) AS INTEGER) mins
  ,mins*weight
FROM (
  SELECT machine, PERIOD(begin, end) AS pd, xpd, BEGIN(xpd) AS begin_xpd 
  FROM run
  EXPAND ON pd AS xpd 
  BY ANCHOR PERIOD ANCHOR_HOUR
  ) x
JOIN weights
ON begin_xpd = TheHour;

相关问题