Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL: Return only first occurrence

I seldomly use SQL and I cannot find anything similar in my archive so I'm asking this simple query question: I need a query which one returns personID and only the first seenTime

Records:

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

Wanted result:

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

That's what I did & failed:

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: Notice SQL CE 4

like image 263
Nime Cloud Avatar asked Jan 04 '12 15:01

Nime Cloud


People also ask

How do I find the first occurrence of a value in SQL?

MySQL LOCATE() Function The LOCATE() function returns the position of the first occurrence of a substring in a string. If the substring is not found within the original string, this function returns 0.

How do I get the first occurrence of a string in SQL?

Searching from the start of a string expression. This example returns the first location of the string is in string This is a string , starting from position 1 (the first character) of This is a string . SELECT CHARINDEX('is', 'This is a string');

How do you select the first record in a group by SQL?

To do that, you can use the ROW_NUMBER() function. In OVER() , you specify the groups into which the rows should be divided ( PARTITION BY ) and the order in which the numbers should be assigned to the rows ( ORDER BY ). You assign the row numbers within each group (i.e., year).

How do I select a single record for duplicates in SQL?

Using the GROUP BY clause to group all rows by the target column(s) – i.e. the column(s) you want to check for duplicate values on. Using the COUNT function in the HAVING clause to check if any of the groups have more than 1 entry; those would be the duplicate values.


2 Answers

If your seenTime increases as seenID increases:

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

Update for another case:

If this is not the case, and you really want the seenTime that corresponds with the minimum seenID (assuming seenID is unique):

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
like image 181
Tim Lehner Avatar answered Oct 18 '22 21:10

Tim Lehner


You're making it way too difficult:

select personID, min(seenTime)
from personAttendances
group by personID
like image 20
Joe Avatar answered Oct 18 '22 23:10

Joe