在关系数据模型中表示调度/时间表

时间:2014-02-21 06:10:42

标签: sql oracle

我们有一个外汇定价系统,我们需要代表在某一天的某一天+一天中的某个时间有效的ECN /交易所。因此可以表示作为行活动的开始时间,结束时间和ECN名称。复合主键将是开始时间+结束时间+ ECN。例如。 -MTWThF- 08:00伦敦,-TTWThF- 14:30纽约,EBS。现在不能有重叠或重复。人们可以编辑记录,约束应该成立。

如何在数据库级别最好地表示这一点?如果它有助于我们使用Oracle,则首选Oracle无关的解决方案。

现在忽略时区&夏令时使得无法避免重叠。

1 个答案:

答案 0 :(得分:1)

我将给出两个答案,首先,考虑RFC 5545中的重复规则格式,并在应用层验证。

由于这可能不是您正在寻找的答案,我还建议将本周的任何一点视为与本周开始的偏差。

然后,您可以构建一个转换列表,用于定义交易所打开或关闭周的偏移量。唯一需要的约束是验证偏移是否有效(少于7天),并且开放到闭合转换后面只有闭合到开放转换(反之亦然)。

我没有开放的oracle框可以玩,但这是T-SQL中的一个示例:

create table #sched (exchangeID int, weekOffset int, isOpen bit)
insert into #sched 
values (1, 400, 1),
    (1, 800, 0),
    (1, 1200, 1),
    (1, 1700, 0);

-- constraints are that isOpen cannot be repeated.  1->0->1 is valid, 1->1->0 is not

declare @coffset int,
    @weekStart datetime;

set @weekstart = dateadd(week, datediff(week, 0, getdate()), 0);
set @coffset = datediff(minute, @weekStart, getdate());

with trans (uniqid, exch, offset, isopen)
as 
(
    select ROW_NUMBER() OVER (ORDER BY weekoffset), *
    from (
        SELECT exchangeID, weekoffset - 7*24*60 as weekoffset, isopen from #sched
        UNION 
        select exchangeID, weekoffset, isopen from #sched
        UNION
        select exchangeID, weekoffset + 7*24*60, isopen from #sched
    ) as inr
)
select *,
    CASE pt.IsOpen 
        WHEN 1 THEN 'Exchange is now open and will close at ' + CAST(DATEADD(minute, nt.offset, @weekstart) as varchar(20)) 
        ELSE 'Exchange is now closed and will open at ' + CAST(DATEADD(minute, nt.offset, @weekstart) as varchar(20)) END
from (
    SELECT MIN(uniqid) as nextTransition
    FROM trans
    WHERE offset > @coffset
) as n
cross join (
    SELECT MAX(uniqid) as prevTransition
    FROM trans
    WHERE offset <= @coffset
) as p
inner join trans as nt on nt.uniqid = nextTransition
inner join trans as pt on pt.uniqid = prevTransition

drop table #sched
sqlfiddle上的

Results

| NEXTTRANSITION | PREVTRANSITION | UNIQID | EXCH | OFFSET | ISOPEN |                                                   COLUMN_10 |
|----------------|----------------|--------|------|--------|--------|-------------------------------------------------------------|
|              9 |              8 |      9 |    1 |  10480 |      1 | Exchange is now closed and will open at Feb 24 2014  6:40AM |