17

我很少使用 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

这就是我所做的并且失败了:

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

PS:注意 SQL CE 4

4

5 回答 5

32

如果您的 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
于 2012-01-04T15:31:28.400 回答
15

你太难了

select personID, min(seenTime)
from personAttendances
group by personID
于 2012-01-04T15:31:42.867 回答
4

对于PostgreSQL,有DISTINCT ON

于 2020-01-09T13:43:41.050 回答
-1

您需要按看到的时间而不是按看到的 id 订购:

PARTITION BY seenID ORDER BY seenTime
于 2012-01-04T15:30:46.563 回答
-2

将此添加到您的 SQL 中:

and where not exists
    (select 1 from personAttendances t2 
    where t.personID=t2.personID 
    and t2.seenID < t.seenID)
于 2012-01-04T15:30:37.360 回答