3

我试图在按字母顺序排序后仅返回查询的第一个结果:

SELECT MIN(DisplayName) FROM [User] GROUP BY DisplayName

我相信上面的方法可以解决问题。但它仍然按字母顺序返回所有结果。我怎样才能得到想要的结果?

4

8 回答 8

7

你不需要GROUP BY

SELECT MIN(DisplayName) 
FROM [User] 

或者:

SELECT TOP 1 DisplayName
FROM [User]
ORDER BY DisplayName

GROUP BY将为列出的字段返回每个不同的值/值组合。

于 2013-09-17T19:02:52.430 回答
1

只有第一行?只需通过以下方式删除组:

SELECT MIN(DisplayName) FROM [User]
于 2013-09-17T19:03:31.203 回答
1

要返回第一条记录,您可以尝试以下操作:

Select TOP 1 MIN(DisplayName) FROM [User] ORDER BY DisplayName

这将按升序排序并选择第一条记录

于 2013-09-17T19:04:26.103 回答
1

如果您想获取“结果”然后加入另一个表,这是一种不同的方法。

Use Northwind
GO


Select derived1.CustomerID, o.*  from dbo.Orders o
join
(
SELECT top 1 CustomerID FROM [Customers] customers ORder by CustomerID
) as derived1
on derived1.CustomerID = o.CustomerID
于 2013-09-17T19:31:21.803 回答
1

我认为您希望每个名称初始化一条记录,如果是这样,请尝试以下操作

这是工作演示SQLFiddle

SELECT Left(DisplayName , 1) , MIN(DisplayName) FROM [User] GROUP BY Left(DisplayName , 1)

于 2013-09-17T19:45:05.007 回答
0
select top 1 city, Len(city)
from station
group by Len(city), city
order by Len(city) asc

select top 1 city, Len(city)
from station
group by Len(city), city
order by Len(city) desc
于 2017-05-09T02:28:22.373 回答
0

如果您使用 ORACLE 作为 SQL IDE;

SELECT City, LENGTH(City)
FROM (SELECT City
      FROM Station
     ORDER BY LENGTH(City), City)
WHERE ROWNUM = 1;
SELECT City, LENGTH(City)
FROM (SELECT City
      FROM Station
     ORDER BY LENGTH(City) DESC, City)
WHERE ROWNUM = 1;
于 2021-05-26T13:00:04.587 回答
-1
select city, 
       length(city) 
from (select city,
             length(city) 
      from station 
      where length(city) in (select min(length(city)) from station) 
order by city asc) where rownum<=1;
select city,
       length(city) 
from station 
where length (city) in (select max(length(city)) from station);
于 2020-06-09T07:11:33.300 回答