我试图在按字母顺序排序之后返回查询的第一个结果:
SELECT MIN(DisplayName) FROM [User] GROUP BY DisplayName
我相信上面的做法会成功。但它仍然按字母顺序撤回所有结果。如何获得所需的结果?
答案 0 :(得分:7)
您不需要GROUP BY
:
SELECT MIN(DisplayName)
FROM [User]
OR:
SELECT TOP 1 DisplayName
FROM [User]
ORDER BY DisplayName
GROUP BY
将返回列出的字段的每个不同值/值组合。
答案 1 :(得分:1)
只有第一排?只需删除该组:
SELECT MIN(DisplayName) FROM [User]
答案 2 :(得分:1)
要返回第一条记录,您可以尝试以下操作:
Select TOP 1 MIN(DisplayName) FROM [User] ORDER BY DisplayName
这将按升序排序,它将选择第一个记录
答案 3 :(得分:1)
如果您想获取“结果”然后加入antoher表,这是一种不同的方法。
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
答案 4 :(得分:1)
我认为您希望每个名称初始化一条记录,然后尝试按照
这是工作演示SQLFiddle
SELECT Left(DisplayName,1),MIN(DisplayName)FROM [User] GROUP BY Left(DisplayName,1)
答案 5 :(得分: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
答案 6 :(得分: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;
答案 7 :(得分:-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);