获取SQL中每个标识符组的第一条记录

时间:2011-02-03 10:08:03

标签: sql sql-server-2008 group-by distinct

Code     Description     Whatever
---------------------------------
1        stuff           blah
1        something       meh
2        yah             bong
2        never           hammer time

如何从每个Code出现一次,从而获得结果集? (我并不过分关心该代码的记录)。

所以我想......

1        stuff           blah
2        yah             bong

2 个答案:

答案 0 :(得分:0)

SELECT *
FROM (
SELECT * , row_number() over(partition by code order by Description) as id
from yourTable
) temp
WHERE id = 1

我认为这只是sql server

答案 1 :(得分:0)

首先需要选择一个确定“第一个结果”的列。在我的示例中,我选择了Description

SELECT * FROM YourTable first 
WHERE 
   (SELECT COUNT(*) FROM YourTable previous 
    WHERE previous.Code=first.Code AND previous.Description < first.Description) = 0