2012-01-04 183 views
5

我罕使用SQL,我無法找到我的檔案,所以我問這個簡單的查詢問題,類似的話:我需要哪一個返回PERSONID,只有第一seenTime查詢SQL:只返回第一次出現

記錄:

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

回答

10

如果您seenTime隨着seenID增加:

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

更新FO R安置另一個案例:

如果不是這種情況,你真的想與最低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 
+0

謝謝!很簡單,因爲我希望......我用MAX很多次,但MIN ... – 2012-01-04 15:41:21

-1

添加到您的SQL。

,並在那裏不存在(選擇1從personAttendances t2的 其中t.personID = t2.personID 和t2.seenID < t.seenID)

0

您需要通過上線時間命令不被看到ID:

PARTITION BY seenID ORDER BY seenTime 
6

你讓方式太難了:

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

由於下午6點的。謝謝! – 2012-01-04 15:40:34