简体   繁体   中英

How can I select multiple columns for a condition with a single where statement?

I am doing some outlier detection for calculations at different time horizons.

How can I clean up the following in Vertica SQL?

Select * FROM my_table
WHERE (    
         (expected_value * 100) > measure_10_sec 
      OR (expected_value * 100) > measure_20_sec
      OR (expected_value * 100) > measure_30_sec
      OR (expected_value * 100) > measure_40_sec
      OR (expected_value * 100) > measure_50_sec
      OR (expected_value * 100) > measure_60_sec
)

To a more nifty query like this:

Select * FROM my_table
WHERE (expected_value* 100) > (measure_10_sec, measure_20_sec, measure_30_sec, measure_40_sec, measure_50_sec, measure_60_sec)

Just use LEAST() :

select * 
from my_table
where (expected_value * 100) > least(measure_10_sec, measure_20_sec, measure_30_sec, measure_40_sec, measure_50_sec, measure_60_sec)

If expected_value * 100 is greater than one of the values, then it is greater than the smallest of the values.

Note: This assumes that all the measures are non- NULL .

If AND were used instead of OR , then you would use GREATEST() .

You can use ANY to check if the left operator satisfies an operation with any right operator from a subquery.

...
WHERE expected_value * 100 > ANY(SELECT measure_10_sec
                                 UNION ALL
                                 SELECT measure_20_sec
                                 ...
                                 UNION ALL
                                 SELECT measure_50_sec
                                 UNION ALL
                                 SELECT measure_60_sec)
...

Note: I'm not sure if your DBMS supports the SELECT without FROM syntax. The documentation suggests it, but you probably need to find another subquery to get the values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM