SQL:仅返回第一次出现

时间:2012-01-04 15:28:11

标签: sql sql-server-ce sql-server-ce-4

我很少使用SQL而且我在档案中找不到任何类似的内容所以我问这个简单的查询问题:我需要一个查询,其中一个返回 personID ,只有第一个 seenTime < /强>

记录:

seenID | personID | seenTime
   108      3         13:34
   109      2         13:56
   110      3         14:22
   111      3         14:31
   112      4         15:04
   113      2         15:52

通缉结果:

personID | seenTime
   3         13:34
   2         13:56
   4         15:04

这就是我所做的&amp;失败:

SELECT t.attendanceID, t.seenPersonID, t.seenTime
(SELECT ROW_NUMBER() OVER (PARTITION BY seenID ORDER BY seenID) AS RowNo,
seenID,
seenPersonID,
seenTime
FROM personAttendances) t
WHERE t.RowNo=1

P.S:注意SQL CE 4

5 个答案:

答案 0 :(得分:17)

如果您的seenTime随着seeID的增加而增加:

select personID, min(seenTime) as seenTime
from personAttendances
group by personID

另一案例的更新:

如果不是这种情况,并且您确实希望与最小的visibleID相对应的seenTime(假设seenID是唯一的):

select a.personID, a.seenTime
from personAttendances as a
    join (
        -- Get the min seenID for each personID
        select personID, min(seenID) as seenID
        from personAttendances
        group by personID
    ) as b on a.personID = b.personID
where a.seenID = b.seenID

答案 1 :(得分:8)

你的方式太难了:

select personID, min(seenTime)
from personAttendances
group by personID

答案 2 :(得分:1)

对于PostgreSQL,有DISTINCT ON

答案 3 :(得分:0)

您需要按照看到的时间订购,而不是看到ID:

PARTITION BY seenID ORDER BY seenTime

答案 4 :(得分:-1)

将其添加到您的SQL:

and where not exists
    (select 1 from personAttendances t2 
    where t.personID=t2.personID 
    and t2.seenID < t.seenID)