SQL:仅返回第一次出现

问题描述 投票:7回答:4

我很少使用SQL,我在档案中找不到任何类似的东西,所以我问这个简单的查询问题:我需要一个查询,其中一个返回personID,只有第一个看到的时间

记录:

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

这就是我所做的和失败的:

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

sql sql-server-ce sql-server-ce-4
4个回答
17
投票

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

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

更新另一个案例:

如果不是这种情况,并且您确实希望与最小的seenID相对应的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

8
投票

你做得太难了:

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

0
投票

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

PARTITION BY seenID ORDER BY seenTime

-1
投票

将其添加到您的SQL:

and where not exists
    (select 1 from personAttendances t2 
    where t.personID=t2.personID 
    and t2.seenID < t.seenID)
© www.soinside.com 2019 - 2024. All rights reserved.