简体   繁体   中英

How to get min and max from 7 columns in Hive Hue excluding zeros

I have a table which has 9 columns. Below is the structure of it

原始表结构

I need the min and max of these columns for a row excluding zeros. Below is the required table structure

需要输出

If you see the columns min and max, min is minimum of 7 cols (col1 to col7) in a particular row excluding zero and max is the maximum of the 7 cols (col1 to col7) for that row.

Please help me to accomplish this in hive (hue).

You can use least and greatest to get the min and max, and use when to remove 0 .

select *,
    least(
        case when col1 != 0 then col1 else 99999999 end,
        case when col2 != 0 then col2 else 99999999 end,
        case when col3 != 0 then col3 else 99999999 end,
        case when col4 != 0 then col4 else 99999999 end,
        case when col5 != 0 then col5 else 99999999 end,
        case when col6 != 0 then col6 else 99999999 end,
        case when col7 != 0 then col7 else 99999999 end,
    ) as `Min`
    greatest(
        case when col1 != 0 then col1 else -99999999 end,
        case when col2 != 0 then col2 else -99999999 end,
        case when col3 != 0 then col3 else -99999999 end,
        case when col4 != 0 then col4 else -99999999 end,
        case when col5 != 0 then col5 else -99999999 end,
        case when col6 != 0 then col6 else -99999999 end,
        case when col7 != 0 then col7 else -99999999 end
    ) as `Max`
from mytable

You can use an explicit case expression:

select (case when col1 <> 0 and col1 >= col2 and col1 >= col3 and col1 > =col4 and col1 >= col5 and col1 >= col6 and col1 >= col7
             then col1
             . . .
        end)

This is a lot of typing. It probably suggests that your data is stored incorrectly -- you should have separate rows for each column. You can mimic this by expanding the data and reaggrating:

select name, state, col1, col2, col3, col4, col5, col6, col7,
       min(case when col1 <> 0 then col1 end) as min_value,
       max(case when col1 <> 0 then col1 end) as max_value,
from ((select t.*, col1 as col from t) union all
      (select t.*, col2 as col from t) union all
      (select t.*, col3 as col from t) union all
      (select t.*, col4 as col from t) union all
      (select t.*, col5 as col from t) union all
      (select t.*, col6 as col from t) union all
      (select t.*, col7 as col from t)
     ) x
group by name, state, col1, col2, col3, col4, col5, col6, col7;
      

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