现在我使用MS SQL Server 2008.我想知道是否可以选择同一组的顶级记录。我的表中有3个字段。这是我的表
ID GroupNo FieldOfInterest
0001 G1 Football
0002 G2 Football
0003 G2 Basketball
0004 G3 Golf
0005 G3 Swimming
我想从这张表中选择记录
ID GroupNo FieldOfInterest
0001 G1 Football
0002 G2 Football
0004 G3 Golf
我该怎么做?请帮帮我 问候
答案 0 :(得分:2)
SELECT t1.*
FROM table AS t1
INNER JOIN (
SELECT MIN(ID) AS MinID
FROM table
GROUP BY GroupNo) AS t2
ON t1.id = t2.MinID
假设“最高记录”表示ID最小的记录,因为您尚未提供订单。
答案 1 :(得分:1)
SELECT ID,
GroupNo,
FieldOfInterest
FROM YOUR_TABLE a,
(SELECT MIN(ID) AS ID
FROM YOUR_TABLE
GROUP BY GroupNo) b
WHERE a.ID = b.ID;
在此,我猜top record
您的意思是records with the smallest ID value
。
答案 2 :(得分:0)
SQL Server ROW_NUMBER()函数可以为您解决此问题:
create table interests (
ID int,
GroupNo varchar(2),
FieldOfInterest varchar(20)
)
insert into interests
values (1, 'G1', 'Football'),
(2, 'G2', 'Football'),
(3, 'G2', 'Basketball'),
(4, 'G3', 'Golf'),
(5, 'G3', 'Swimming');
with cte as (
select ROW_NUMBER() OVER (PARTITION BY GroupNo ORDER BY ID) as row, *
from interests
)
select c.ID, c.GroupNo, c.FieldOfInterest
from cte c
where row = 1