0

我有一个这样的sql查询:

SELECT

.....
price

..... AS distance

ORDER BY case
  ...

我的问题是,如何将计算出的距离用作排序元素?

4

2 回答 2

1

我不清楚问题查询中的“距离”是什么,以及您为什么将案例放在 oeder by 中。

通常,您可以在 ORDER BY 子句中通过别名或在 select 子句中的编号来提及字段。您也可以将一些逻辑放入 ORDER BY

  select A,
         B as MyB,
         C - Z, -- <- Field #3: (A - #1, B - #2, C - Z - #3, D + F + G - #4 etc)
         D + F + G
    from MyTable
order by MyB asc,       -- <- by alias
         3 desc,        -- <- by field's number
         D + F + G asc, -- <- by some logic, here it's just copy + paste
         case           -- <- by some logic designed for ORDER BY only
           when (A > B + C) then
             1
           when (A > B)  then
             2
           else    
             3
         end desc
于 2013-08-15T10:24:50.623 回答
0

distanceorder by子句中使用相同的定义:

select 
...
price
<some logic here> as distance
...
order by <same logic here>

或从外部引用派生列select

select * from
(
select
...
price
... as distance
...
) x
order by x.distance
于 2013-08-15T10:02:32.143 回答