SQL 使用交叉引用两个表的结果在视图中创建列

SQL Creating a cloumn in a view with the results from cross-referencing two tables

我是 SQL 的新手,正在尝试创建一个视图,该视图结合了读数数据库和故障数据库中的数据。我想创建一个按目标名称排序的视图,然后是指标名称,然后是时间戳,还有一个附加列 returns 1 表示当天发生故障,否则为零。我写的查询目前正在读取我缺少右括号,但是当我删除括号时它发现 table 名称无效。我不确定我对案例的使用是否导致了它,尽管它已经在一些练习样本上起作用了。任何帮助检查这个以及如何改进它的建议将不胜感激。

SELECT * FROM
(
with new_failure_table as  (
    SELECT target_name, END_TIMESTAMP,START_TIMESTAMP, 
    ((END_TIMESTAMP - (START_TIMESTAMP))*24*60) 
    FROM failure_table 
    WHERE (END_TIMESTAMP - (START_TIMESTAMP))*24*60 >5 
    AND  (END_TIMESTAMP - START_TIMESTAMP) < 1
    and availability_status = 'Target Down'
    ) 
    -- Simplifies failure table to include actual failures according to two parameters

SELECT
    t1.target_name,
    t1.metric_name,
    t1.rollup_timestamp,
    t1.average,
    t1.minimum,
    t1.maximum,
    t1.standard_deviation,
    t2.END_TIMESTAMP,
    t2.START_TIMESTAMP,
    (CASE  
    when t1.target_name = t2.target_name 
    and t1.rollup_timestamp = trunc(END_TIMESTAMP+1) 
    and t1.rollup_timestamp = trunc(START_TIMESTAMP+1) 
    THEN '1' ELSE '0' END) AS failure_status
    --Used to create column that reads 1 when there was a failure between the two readings and 0 otherwise    

FROM
    data_readings AS t1, new_failure_table AS t2 
WHERE t1.target_name = t2.target_name       
)

GROUP BY t1.target_name, metric_name
ORDER BY rollup_timestamp desc;

您不需要将 case 括在括号中,它可以是

CASE  
when t1.target_name = t2.target_name 
and t1.rollup_timestamp = trunc(END_TIMESTAMP+1) 
and t1.rollup_timestamp = trunc(START_TIMESTAMP+1) 
THEN '1' ELSE '0' END AS failure_status

同样在 FROM 中不要使用 AS 而不是:

...
FROM data_readings AS t1, new_failure_table AS t2 
...

使用

...
FROM data_readings t1, new_failure_table t2 
...

UPD:整个查询应如下所示

SELECT * FROM
(
with new_failure_table as  (
    SELECT target_name, END_TIMESTAMP,START_TIMESTAMP, 
    ((END_TIMESTAMP - (START_TIMESTAMP))*24*60) 
    FROM failure_table 
    WHERE (END_TIMESTAMP - (START_TIMESTAMP))*24*60 >5 
    AND  (END_TIMESTAMP - START_TIMESTAMP) < 1
    and availability_status = 'Target Down'
    ) 
    -- Simplifies failure table to include actual failures according to two parameters

SELECT
    t1.target_name as target_name,
    t1.metric_name as metric_name,
    t1.rollup_timestamp as rollup_timestamp,
    t1.average,
    t1.minimum,
    t1.maximum,
    t1.standard_deviation,
    t2.END_TIMESTAMP,
    t2.START_TIMESTAMP,
    CASE  
    when t1.target_name = t2.target_name 
    and t1.rollup_timestamp = trunc(END_TIMESTAMP+1) 
    and t1.rollup_timestamp = trunc(START_TIMESTAMP+1) 
    THEN '1' ELSE '0' END AS failure_status
    --Used to create column that reads 1 when there was a failure between the two readings and 0 otherwise    

FROM
    data_readings t1, new_failure_table t2 
WHERE t1.target_name = t2.target_name       
)
GROUP BY target_name, metric_name
ORDER BY rollup_timestamp desc;