简体   繁体   中英

how to print condition based values in column in mysql query

I have three columns "name","trade" and "score" in table. data example:

name    trade     score
name1   trade1     10
name2   trade1     5
name3   trade1     20
name4   trade1     15

I want to have result with name,status where status can have one of the three values ie "average", "above average" and "below average". where average is the average of "score" column. now based on above data, average score is 12.5. so expcted result will be like this:

name     status
name1    below average
name2    below average
name3    above average
name4    above average

i am not sure if this can be achieved with a single query or with some stored procedure or function. please suggest.

You can use the following query:

SELECT name,
       IF (total_score < average_score, 'below average',
          IF(total_score > average_score, 'above average', 'average')) AS status
FROM (          
  SELECT name, 
         SUM(score) AS total_score, 
         (SELECT AVG(score) FROM mytable) AS average_score
  FROM mytable
  GROUP BY name ) AS t

Demo here

SELECT
    a.name,
    CASE
        WHEN a.score < t.average THEN 'below average'
        WHEN a.score > t.average THEN 'above average'
        ELSE 'average'
    END AS status
FROM
    table1 a,
    (SELECT AVG(score) average FROM table1) t

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