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

时间:2019-05-09 05:02:14

标签: mysql sql

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

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

+--------+--------------+
| id_col | sum          | 
+--------+--------------+
|    123 | 523.99996667 |
+--------+--------------+

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 |
+--------+--------------+----------+---------+------+

我已经尝试过以下方法在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```

3 个答案:

答案 0 :(得分:3)

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

select id_col,SUM(least(coalesce(col1,0),coalesce(col2,0),coalesce(col3,0)))
from tablename
group by id_col

OR

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

答案 1 :(得分:1)

@ fa06答案(+1)的替代方法,您可以首先使用子查询将所有NULL的值合并为零,然后使用逐字查询:

WITH cte AS (
    SELECT
        id,
        id_col,
        COALECSE(col_1, 0) AS col_1,
        COALECSE(col_2, 0) AS col_2,
        COALECSE(col_3, 0) AS col_3
    FROM example_table
)

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) AS sum
FROM cte
GROUP BY id_col;

答案 2 :(得分:1)

对于SQL Server,以下脚本将起作用。您可以在“交叉申请”列表中添加所需的任意列

SELECT B.ID [id_col],SUM(B.least) [SUM]
FROM
(
    SELECT  A.ID,A.RN, MIN(T.CombinedValue) AS least FROM
    (
        SELECT ROW_NUMBER() OVER(PARTITION BY yt.ID ORDER BY ID) RN, * 
        FROM your_table yt
    ) A
    CROSS APPLY ( VALUES ( A.col1 ), ( A.col2 ), ( A.col3 )) AS T (CombinedValue)
    GROUP BY A.ID,A.RN
)B
GROUP BY B.ID