我想做的是以下内容:
SELECT SUM(ABS(`number_x` - `number_y`)) AS `total_difference` FROM `table`
表格如下:
id | number_x |编号y
1 | 4 | 2
2 | 3 | 2
3 | 2 | 4
所以答案应该是: (4-2 = 2)+(3-2 = 1)+(2-4 = 2)= 5
我可以在MySQL中执行此操作吗?
谢谢!
答案 0 :(得分: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
答案 1 :(得分: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