Max() 中的自定义排序

Custom ordering in Max()

假设我有一个 table 'things',其中有一列 'ranking'。 ranking 列中有 5 条记录,值为 First、Second、Third、Fourth 和 Fifth。

我希望能够使用

select Max(ranking) from things

改为 return 'Fifth',而不是默认的 'Third'。

此外,我希望 Fourth 被认为大于 Third,等等

我怎样才能做到这一点?

SQL 服务器 2005

您需要单独查找 table 到 link 这些值到可以排序的数值。

我建议不要使用 max(ranking)

select top 1 ranking
from things
order by ranking desc;

这并没有解决你的问题,但它指明了一个好的方向。只需在 order by:

中使用 case 语句
select top 1 ranking
from things
order by (case ranking
              when 'First' then 1
              when 'Second' then 2
              when 'Third' then 3
              when 'Fourth' then 4
              when 'Fifth' then 5
          end) desc;

您也可以使用辅助 table 或子查询来执行此查找。