问题描述
我有3个表,我需要检查“比率”列中的表是否为正数。 表具有不同的架构,但是它们都有一个名为“ rate”的列。 我正在使用气流,并且创建了一个DAG,它的任务是检查速率是否不是正数,然后失败。 简而言之,如果这些表中的任何一个出现错误的速率,我都希望我的SQL失败。 我已经做到了:
WITH t1 AS (
SELECT deliverydate,rate
FROM table1
WHERE rate <= 0
),t2 AS (
SELECT deliverydate,rate
FROM table2
WHERE rate <= 0
),t3 AS (
SELECT deliverydate,rate
FROM table3
WHERE rate <= 0
)
SELECT 1 FROM (
SELECT * FROM t1
UNION ALL
SELECT * FROM t2
UNION ALL
SELECT * FROM t3
)
在这种情况下,t1,t2和t3将报告错误速率(0或负速率)的行。如果没有错误的速率,则选择1失败。
但是我的目标是: 如果所有速率正确,则通过;如果至少一个记录的速率错误,则失败;然后向我显示该记录以对其进行修复。 >
SQL查询以bigquery标准运行
解决方法
我建议这样的逻辑:
select (case when exists (select 1 from table1 where rate <= 0) then 'FAIL'
when exists (select 1 from table2 where rate <= 0) then 'FAIL'
when exists (select 1 from table3 where rate <= 0) then 'FAIL'
else 'PASS'
end)
这在第一次失败时停止,应该非常有效。为了提高性能,请在每个子表的rate
上添加一个索引。
某些数据库需要from
子句,例如from dual
。
我怀疑这是最好的处理方法,但这仅在使用error()
的错误情况下才会产生错误:
select (case when exists (select 1 from table1 where rate <= 0) then error('Bad rate in table1')
when exists (select 1 from table2 where rate <= 0) then error('Bad rate in table2')
when exists (select 1 from table3 where rate <= 0) then error('Bad rate in table3')
else 'PASS'
end)