开发者

SQL: how to only use dynamic column for order, not as part of result set

开发者 https://www.devze.com 2023-03-17 06:39 出处:网络
I currently have a query that returns a list of columns, and one of those columns I only want to use internally as a sort column, not as a column in the result set.

I currently have a query that returns a list of columns, and one of those columns I only want to use internally as a sort column, not as a column in the result set.

  SELECT Id, Lat, Lng开发者_如何学运维, <haversine calc> as Distance
    FROM Locations
ORDER BY Distance

Based on the above, the only reason I currently include 'Distance' in the the SELECT clause is so I can use it in the ORDER BY clause. My consumer code doesn't use Distance at all.

How can I rewrite this query to only return the columns I'm interested in (Id, Lat, Lng) and not the ones I'm not interested in (Distance), while allowing the sort on Distance?


All you have to do is to move your calculation into your ORDER BY clause like this:

SELECT Id, Lat, Lng
FROM Locations
ORDER BY <haversine calc>


You don't need to include a column in select cause you want to sort on it. You can directly query the cols you want

SELECT Id, Lat, Lng FROM Locations ORDER BY <Your Col>
0

精彩评论

暂无评论...
验证码 换一张
取 消