0

我想做的是以下几点:

SELECT SUM(ABS(`number_x` - `number_y`)) AS `total_difference` FROM `table`

表如下:

编号 | number_x | number_y

1 | 4 | 2

2 | 3 | 2

3 | 2 | 4

所以答案应该是:(4 - 2 = 2) + (3 - 2 = 1) + (2 - 4 = 2) = 5

我可以在 MySQL 中执行此操作吗?如何操作?

谢谢!

4

2 回答 2

3

您发布的查询应该没有问题:

SELECT SUM(ABS(`number_x` - `number_y`)) AS `total_difference` 
FROM `table`

或者,如果您想使用这样的子查询来编写它:

SELECT SUM(diff) AS `total_difference` 
FROM
( 
    SELECT Id, ABS(number_x - number_y) diff
    FROM TableName
) t
于 2012-10-18T11:59:56.800 回答
1
SELECT SUM(ABS(`number_x` - `number_y`)) AS `total_difference` FROM `table`

或者你可以用其他方式写,但我只喜欢上面

SELECT ABS(SUM(number_x) - SUM(number_y)) AS total_difference FROM table
于 2012-10-18T11:59:48.703 回答