从几列中选择最小值然后计算其总和的最佳方法是什么?

Coo*_*ter 1 mysql sql

我正在尝试:1)在col_1,col_2和col_3之间选择最小值。2)根据id_col值计算最小值的总和。

使用下面的示例表,我期望的结果是:

+--------+--------------+
| id_col | sum          | 
+--------+--------------+
|    123 | 523.99996667 |
+--------+--------------+
Run Code Online (Sandbox Code Playgroud)

example_table

+--------+--------------+----------+---------+------+
| id_col | col_1        | col_2    | col_3   | id   |
+--------+--------------+----------+---------+------+
|    123 | 175.00000000 | 150.0000 |    NULL | 999  |
|    123 | 175.00000000 | 150.0000 |    NULL | 999  |
|    123 | 175.00000000 | 150.0000 |    NULL | 999  |
|    123 |  41.66666667 |  50.0000 |    NULL | 4444 |
|    123 |  50.00000000 | 100.0000 | 32.3333 | 5555 |
+--------+--------------+----------+---------+------+
Run Code Online (Sandbox Code Playgroud)

我在下面尝试过在3列之间选择最小值,但是它只是在整个表格中选择最小值。

select id_col,
SUM(CASE WHEN col_1 < col_2 AND col_1 < col_3 THEN col_1
            WHEN col_2 < col_1 AND col_2 < col_3 THEN col_2
            ELSE col_3 END) sum
from example_table
group by 1```
Run Code Online (Sandbox Code Playgroud)

Fah*_*hmi 5

如果您的dbms是mysql,则可以使用 least()

select id_col,SUM(least(coalesce(col1,0),coalesce(col2,0),coalesce(col3,0)))
from tablename
group by id_col
Run Code Online (Sandbox Code Playgroud)

要么

select id_col,
SUM(CASE WHEN coalesce(col_1,0) < coalesce(col_2,0) AND coalesce(col_1,0) < coalesce(col_3,0) THEN col_1
            WHEN oalesce(col_2,0) < oalesce(col_1,0) AND oalesce(col_2,0) < oalesce(col_3,0) THEN col_2
            ELSE oalesce(col_3,0) END) sum
from example_table
group by 1
Run Code Online (Sandbox Code Playgroud)