私がやりたいことは次のとおりです。
SELECT SUM(ABS(`number_x` - `number_y`)) AS `total_difference` FROM `table`
表は次のとおりです。
id | number_x | number_y
1 | 4 | 2
2 | 3 | 2
3 | 2 | 4
したがって、答えは次のようになります。(4-2 = 2)+(3-2 = 1)+(2-4 = 2)= 5
MySQLでこれを行うことはできますか?
ありがとう!
投稿したクエリは問題なく機能するはずです。
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
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