表间查询:我需要根据其他两个表中的条件构建一个过滤数据的查询

时间:2017-10-25 18:58:46

标签: sql

我有3张表格如下

data 
timestamp   : col1: col2: col3
-------------------------------- 
2017-03-12  : 2.2 : 3.3: 5.1 
2017-06-10  : 1.2 : 1.3: 2.1

offset 
starttime  : endtime    : col1 : col2 : col3
------------------------------------------ 
2017-03-10 : 2017-03-13 : 0.5  :  0.7 : 0.1 
2017-06-09 : 2017-06-12 : 1    :   2  :  3

flag 
timestamp   : col1: col2: col3
------------------------------- 
2017-03-12  : 0   : 0   : 1 
2017-06-10  : 1   : 0   : 1

我想构建一个查询,给出以下结果:

data.timestamp,
offset.starttime,
offset.endtime, 
CASE WHEN flag.col1=0 < THEN NULL ELSE data.Col1 + offset.Col1 AS COL1 END,
CASE WHEN flag.col2=0 < THEN NULL ELSE data.Col2 + offset.Col2 AS COL2 END,
CASE WHEN flag.col3=0 < THEN NULL ELSE data.Col3 + offset.Col3 AS COL3 END
where data.TimeStamp Between offsett.StarTime and offset.EndTime
例如

,例如

结果将是:考虑数据和偏移表,结果如下:

TimeStamp   : offset.StartTime : offset.EndTime : COL1 : COL2 : COL3
--------------------------------------------------------------------- 
2017-03-12  :    2017-03-10    :    2017-03-13  : 2.7   : 4.0 : 5.2 
2017-06-10  :    2017-06-09    :    2017-06-12  : 2.2   : 2.3 : 5.1

但是通过在标志表中添加第三个条件,最终结果将是:

TimeStamp   : offset.StartTime : offset.EndTime : COL1 : COL2 : COL3
--------------------------------------------------------------------- 
2017-03-12  :    2017-03-10    :    2017-03-13  : NULL : NULL : 5.2 
2017-06-10  :    2017-06-09    :    2017-06-12  : 2.2  : NULL : 5.1

Is it possible to build such a query thanks

1 个答案:

答案 0 :(得分:0)

看起来你只需要一个简单的连接:

T(n) = a' + (1 + log_3(n))c' = O(log_3(n)) = O(log n)

我建议您将select data.timestamp, offset.starttime, offset.endtime, CASE WHEN flag.col1=0 < THEN NULL ELSE data.Col1 + offset.Col1 AS COL1 END as Col1, CASE WHEN flag.col2=0 < THEN NULL ELSE data.Col2 + offset.Col2 AS COL2 END as Col2, CASE WHEN flag.col3=0 < THEN NULL ELSE data.Col3 + offset.Col3 AS COL3 END as Col3 from data join offset on data.TimeStamp between offset.StarTime and offset.EndTime join flag on flag.TimeStamp = data.TimeStamp 列重命名为TimeStamp,因为它们会存储日期而不是时间戳。