我有一个像这样的SQL查询:
SELECT
.....
price
..... AS distance
ORDER BY case
...
我的问题是,我如何将计算出的距离用作排序元素?
答案 0 :(得分:1)
我不清楚问题查询中的“距离”是什么以及为什么要将案件放在oeder中。
通常,您可以在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
答案 1 :(得分:0)
在distance
子句中对order 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