总而言之,用例将传入值与另一列进行比较(MYSQL)

时间:2018-08-03 03:16:06

标签: mysql sql

即:

| id | num |
| a  | 1   |
| b  | 2   |
| c  | 3   |
| d  | 4   |
| e  | 5   |

而这个查询本质上就是我想要做的:

select num as number, sum(case num > number then num else 0 end) as summation from table;

(我正在尝试对大于num列中当前选择的num的所有整数求和。)

上表中的示例输出:

| num | summation |
| 1   | 14        |
| 2   | 12        |
| 3   | 9         |
| 4   | 5         |
|5    | 0         |

问题在于我不能使用在同一选择语句中定义的别名。还有另一种方法吗?
谢谢!

4 个答案:

答案 0 :(得分:1)

如果您使用的是MySQL 8.0,则可以使用窗口功能。

SELECT num,
       sum(num) OVER (ORDER BY num DESC) - num summation
       FROM elbat
       ORDER BY num;

在MySQL 8.0之前,您可以使用相关的子查询。

SELECT t1.num,
       coalesce((SELECT sum(t2.num)
                        FROM elbat t2
                        WHERE t2.num > t1.num),
                0) summation
       FROM elbat t1
       ORDER BY t1.num;

答案 1 :(得分:1)

您可以使用相关子查询来编写它:

select num,
       (select sum(num)
        from t 2
        where t2.num >= t.num
       ) - num as summation
from t;

答案 2 :(得分:1)

您可以使用 correlated 子查询:

select num,
       (select sum(num)
        from table t2
        where t2.num > t.num
       ) as summation 
from table t1;

答案 3 :(得分:0)

这很有用,尽管有点混乱:

select num, (select sum(case when table.num > temp.num then num else 0 end)
  from (select * from table) as temp
) as summation
from table;