3
<asp:SqlDataSource ID="dsSearchResults" runat="server" 
                ConnectionString="<%$ ConnectionStrings:strConn %>" 
    <SelectCommand="SELECT StoreNumber, StoreName, Address, City, State, PostalCode, Phone, Email, Latitude, Longitude, SQRT(POWER(Latitude - @Latitude, 2) + POWER(Longitude - @Longitude, 2)) * 62.1371192 AS DistanceFromAddress 
                    FROM Stores 
                    WHERE (ABS(Latitude - @Latitude) &lt; 1.75) AND (ABS(Longitude - @Longitude) &lt; 1.75) 
                    ORDER BY DistanceFromAddress">
   <SelectParameters>

我想将搜索结果限制为前 5 个结果。我尝试了几种不同的方法,但无济于事。是的,我是新手,但想学习。我正在使用 SQL Server 2012。

4

4 回答 4

2

您可以像这样更改 SQL 命令:

SELECT TOP 5 StoreNumber, StoreName, Address, City, 
State, PostalCode, Phone, Email, Latitude, Longitude, 
SQRT(POWER(Latitude - @Latitude, 2) 
+ POWER(Longitude - @Longitude, 2)) * 62.1371192 AS DistanceFromAddress 
FROM Stores WHERE (ABS(Latitude - @Latitude) &lt; 1.75) 
AND (ABS(Longitude - @Longitude) &lt; 1.75) 
ORDER BY DistanceFromAddress
于 2013-07-18T16:45:41.820 回答
1

SQL Server 使用TOP语句来限制查询结果。

在您的情况下,查询将是

SELECT TOP 5 StoreNumber, StoreName, Addres...
于 2013-07-18T16:45:40.490 回答
0

SQL Server 2012允许您FETCH OFFSETORDER BY子句中使用:

SELECT (all your columns) 
FROM Stores 
WHERE 
     (ABS(Latitude - @Latitude) &lt; 1.75) AND (ABS(Longitude - @Longitude) &lt; 1.75) 
ORDER BY DistanceFromAddress
OFFSET 100 ROWS
FETCH NEXT 50 ROWS ONLY;

这将跳过前 100 行,并从那里返回 50 行。使用这种方法,您不仅可以选择前 (n) 行 - 还可以选择结果集中某处的任何 (n) 行 - 非常适合将结果分页到每页 (n) 行。

因此,如果您只想排在前 5 行,请使用

....
ORDER BY DistanceFromAddress
OFFSET 0 ROWS
FETCH NEXT 5 ROWS ONLY;
于 2013-07-18T16:58:59.117 回答
0

尝试在查询中使用 TOP:

SELECT top 5 StoreNumber, StoreName, Address, City, State, PostalCode, Phone, Email, 
Latitude, Longitude, SQRT(POWER(Latitude - @Latitude, 2) + POWER(Longitude - @Longitude, 2)) *
62.1371192 AS DistanceFromAddress FROM Stores WHERE (ABS(Latitude - @Latitude) &lt; 1.75) AND 
(ABS(Longitude - @Longitude) &lt; 1.75) ORDER BY DistanceFromAddress limit 
于 2013-07-18T16:47:05.250 回答