我正在尝试: 1) 选择 col_1、col_2 和 col_3 之间的最小值 2) 根据id_col值计算最小值之和。
使用下面的示例表,我期望的结果是:
+--------+--------------+
| id_col | sum |
+--------+--------------+
| 123 | 523.99996667 |
+--------+--------------+
示例表
+--------+--------------+----------+---------+------+
| 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 |
+--------+--------------+----------+---------+------+
我已尝试在下面选择 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```
最佳答案
如果你的 dbms 是 mysql 那么你可以使用 least()
select id_col,SUM(least(coalesce(col1,0),coalesce(col2,0),coalesce(col3,0)))
from tablename
group by id_col
或
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
关于mysql - 从多列中选择最小值然后计算它们的总和的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56052491/