如何按自定义顺序对T-SQL查询输出进行排序?

时间:2018-10-03 05:58:02

标签: sql sql-server tsql sql-order-by

我正在使用SQL Server 2014。我需要将T-SQL查询的输出按特定顺序排序。

我已经尝试了以下方法,但是它没有达到我的预期。这是我的T-SQL查询的最后一部分的摘录:

...  
GROUP BY xx.[Market]

ORDER BY CASE
WHEN xx.[Market] = 'France' THEN '1'
WHEN xx.[Market] = 'United Kingdom' THEN '2'
WHEN xx.[Market] = 'Germany' THEN '3'
WHEN xx.[Market] = 'Belgium' THEN '4'
WHEN xx.[Market] = 'Reunion' THEN '5'
WHEN xx.[Market] = 'South Africa' THEN '6'
WHEN xx.[Market] = 'Russia' THEN '7'
WHEN xx.[Market] = 'Middle East' THEN '8'
WHEN xx.[Market] = 'Central Europe' THEN '9'
WHEN xx.[Market] = 'Poland' THEN '10'
WHEN xx.[Market] = 'Scandinavia' THEN '11'
WHEN xx.[Market] = 'Netherlands' THEN '12'
WHEN xx.[Market] = 'India' THEN '13'
WHEN xx.[Market] = 'G&I' THEN '14'
WHEN xx.[Market] = 'China' THEN '15'
WHEN xx.[Market] = 'OTA' THEN '16'
WHEN xx.[Market] = 'Web Direct' THEN '17'
WHEN xx.[Market] = 'DB Local' THEN '18'
WHEN xx.[Market] = 'DB International' THEN '19'
WHEN xx.[Market] = 'Other Markets' THEN '20'

ELSE xx.[Market] END

但是,我得到以下结果:

Market               RN
France               196
Scandinavia           80
Netherlands          320
India                  2
OTA                  372
Web Direct           140
DB Local              11
DB International      25
United Kingdom     2,424
Other Markets        116
Germany              609
Belgium              350
Reunion               27
South Africa          42
Russia                 7
Central Europe        17
Switzerland           34

是因为某些市场未包含在产出中吗?如果是,我将如何处理此问题(因为当我将查询与其他过滤器一起使用时,在某些情况下可能会出现此输出中缺少的市场)?

1 个答案:

答案 0 :(得分:6)

不要在CASE子句中使用字符串值,而应使用数字值。

ORDER BY CASE
WHEN xx.[Market] = 'France' THEN 1
WHEN xx.[Market] = 'United Kingdom' THEN 2
...
ELSE 1000
END