我试图在按字母顺序排序后仅返回查询的第一个结果:
SELECT MIN(DisplayName) FROM [User] GROUP BY DisplayName
我相信上面的方法可以解决问题。但它仍然按字母顺序返回所有结果。我怎样才能得到想要的结果?
我试图在按字母顺序排序后仅返回查询的第一个结果:
SELECT MIN(DisplayName) FROM [User] GROUP BY DisplayName
我相信上面的方法可以解决问题。但它仍然按字母顺序返回所有结果。我怎样才能得到想要的结果?
你不需要GROUP BY
:
SELECT MIN(DisplayName)
FROM [User]
或者:
SELECT TOP 1 DisplayName
FROM [User]
ORDER BY DisplayName
GROUP BY
将为列出的字段返回每个不同的值/值组合。
只有第一行?只需通过以下方式删除组:
SELECT MIN(DisplayName) FROM [User]
要返回第一条记录,您可以尝试以下操作:
Select TOP 1 MIN(DisplayName) FROM [User] ORDER BY DisplayName
这将按升序排序并选择第一条记录
如果您想获取“结果”然后加入另一个表,这是一种不同的方法。
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
我认为您希望每个名称初始化一条记录,如果是这样,请尝试以下操作
这是工作演示SQLFiddle
SELECT Left(DisplayName , 1) , MIN(DisplayName) FROM [User] GROUP BY Left(DisplayName , 1)
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
如果您使用 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;
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);