mysql - 从多列中选择最小值然后计算它们的总和的最佳方法是什么?

标签 mysql sql

我正在尝试: 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/

相关文章:

mysql - mysql query_cache_min_res_unit 的最小值

javascript - 在 mysql 中通过别名获取行后无法生成 json 数据

php - 在 SELECT 查询中使用 *

mysql - 在 MYSQL 中查询以获取来自另一个查询的两个值的结果

sql - 单行子查询返回多行

mysql : Get latest value and sum of values from previous hour

php - MySQL 子查询无法循环数据

sql - 使用 CONNECT BY PRIOR 进行分层查询 - Oracle SQL

java - 如何将实体添加到数据库而不在数据库中添加相关实体?

类似 SQL 的 Windows 注册表包装器?