简体   繁体   中英

SQL query to get average as below case or how to use hibernate criteria

Column Mode:   0 1 0 1
Column Value1: 5 6 4 8
Column Value2: 10 7 5 20

How to get Avg based on Mode eg for mode 0 , it will take value from Value1 column and 1 , it will take value from Value2 column

Avg = (5 + 7 + 4 + 20)/4 =9

below may work

 select (val1+val2)/2 from 
    (select sum(case when mode =0 then value1 end) as val1 ,
     sum(case when mode=1 then value2 end) as val2
    ) t

Or

select avg(case mode when 0 then Value1
                 when 1 then Value2
                   else 0 end) from t

You can use mysql CASE statement to chose value1 or value2 based upon value of mode. The below query should work for you.

SELECT 
    AVG(CASE
        WHEN mode = 0 THEN value1
        WHEN mode = 1 THEN value2
    END)
FROM test

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