按列值差异排序

时间:2019-12-18 02:54:46

标签: mysql sql

我的sql数据库表cities中有以下几列:

  

邮政编码| totalPet人口| numCats | numDogs

我的目标是获取numCats> numDogs的所有行,但我还需要根据numCats和numDogs之间的差异以降序对其进行排序。也就是说,如果我有下表:

zipcode | totalPetPopulation | numCats | numDogs 
44412   | 45                 | 10      | 35
15442   | 80                 | 50      | 30
44133   | 90                 | 70      | 20
90293   | 11                 | 5       | 6
11123   | 25                 | 20      | 5

我需要的结果是:

44133 | 90 | 70 | 20 (difference is 70 - 20 = 50)
15442 | 80 | 50 | 30 (difference is 50 - 30 = 20)
11123 | 25 | 20 | 5  (difference is 20 - 5 = 15)

到目前为止,我可以查询以下内容:

SELECT * FROM cities WHERE numCats > numDogs;

1 个答案:

答案 0 :(得分:3)

您只需将差异表达式放在ORDER BY子句中即可:

SELECT *
FROM cities
WHERE numCats > numDogs
ORDER BY (numCats - numDogs) DESC

输出:

zipcode     totalPetPopulation  numCats     numDogs
44133       90                  70          20
15442       80                  50          30
11123       25                  20          5

Demo on dbfiddle