简体   繁体   中英

Mapping enum to values/weights for SUM in MySQL

I'm trying to craft a query similar to this:

SELECT id, SUM(my_column) FROM my_table GROUP BY my_column

Where my_column is not a number but is an enum.

For illustration purposes, imagine it's a size (small/medium/large) and I want the value of small to be 1, medium to be 10, and large to be 100. How would I map the enum to those integers to be used in the SUM function?

I've been looking at stored procedures and the CREATE FUNCTION syntax but I'm not sure whether that's the route to go. Basically if I could create something like this that would be great but I'm not sure how to go about it in MySQL:

SELECT id, SUM(GET_VALUE_OF(my_column)) FROM my_table GROUP BY my_column;

Where GET_VALUE_OF would be defined as something like

GET_VALUE_OF = function(v) {
    switch(v) {
        case 'small': return 1;
        case 'medium': return 10;
        case 'large': return 100;
        default: return 0;
    }
}

You can create a deterministic function:

delimiter $$
drop function if exists get_value_of$$
create function get_value_of(v varchar(50))
returns int deterministic
begin

    case v
      when 'small'  then return 1;
      when 'medium' then return 10;
      when 'large' then return 100;
      else  
        return 0;
    end case;

end$$
delimiter ;

And you can use that in your queries:

mysql> select id, size , get_value_of(size) as val from my_table;
+----+--------+------+
| id | size   | val  |
+----+--------+------+
|  1 | small  |    1 |
|  2 | medium |   10 |
|  3 | large  |  100 |
|  4 | other  |    0 |
+----+--------+------+
4 rows in set (0.02 sec)

Also in aggregate functions:

mysql> select sum(get_value_of(size)) as total from my_table;
+-------+
| total |
+-------+
|   111 |
+-------+
1 row in set (0.00 sec)

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