Please start any new threads on our new
site at https://forums.sqlteam.com. We've got lots of great SQL Server
experts to answer whatever question you can come up with.
| Author |
Topic |
|
loxt
Starting Member
4 Posts |
Posted - 2012-07-24 : 01:44:10
|
| Hi,I have a problem relating to a similiar table like this:table_locationsuserID timestamp locationIDA 1 cA 3 aA 2 dA 4 bB 3 aB 2 cB 1 bC 4 bC 1 aC 3 dC 2 cI need a list with the earliest locationIDs for every user.I need:userID locationIDA cB bC aSo I thought about:select locationIDfrom table_locationswhere userID and timestamp IN(select userID, min(timestamp)from table_locationsgroup by userID)But the IN-operator can just handle a list of the same values...Thanks a lot. |
|
|
lionofdezert
Aged Yak Warrior
885 Posts |
Posted - 2012-07-24 : 02:14:48
|
| CREATE TABLE #table_locations (userID CHAR(5), timestampp INT, locationID CHAR(5))INSERT INTO #table_locationsSELECT 'A', 1, 'c' UNION ALLSELECT 'A', 3, 'a' UNION ALLSELECT 'A', 2, 'd' UNION ALLSELECT 'A', 4,' b' UNION ALLSELECT 'B', 3 ,'a' UNION ALLSELECT 'B', 2, 'c' UNION ALLSELECT 'B', 1, 'b' UNION ALLSELECT 'C', 4, 'b' UNION ALLSELECT 'C', 1, 'a' UNION ALLSELECT 'C', 3, 'd' UNION ALLSELECT 'C' ,2, 'c';WITH CTEAS(SELECT userID,locationID, ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY timestampp) RowNum FROM #table_locations) SELECT userID,locationID FROM CTEWHERE RowNum = 1DROP TABLE #table_locations--------------------------http://connectsql.blogspot.com/ |
 |
|
|
loxt
Starting Member
4 Posts |
Posted - 2012-07-24 : 02:45:50
|
| Thank you, that was exactly what I was looking for! |
 |
|
|
lionofdezert
Aged Yak Warrior
885 Posts |
Posted - 2012-07-24 : 02:52:45
|
| My pleasure--------------------------http://connectsql.blogspot.com/ |
 |
|
|
loxt
Starting Member
4 Posts |
Posted - 2012-07-24 : 03:23:31
|
| Well, how could I get the locationID for every userID at the highest timestamp?So I need:userID locationIDA bB aC bunfortunatelly for every userID there are different numbers of entries...Thanks! |
 |
|
|
lionofdezert
Aged Yak Warrior
885 Posts |
Posted - 2012-07-24 : 03:26:20
|
| ;WITH CTEAS(SELECT userID,locationID, ROW_NUMBER() OVER (PARTITION BY UserID ORDER BY timestampp DESC ) RowNum FROM #table_locations)SELECT userID,locationID FROM CTEWHERE RowNum = 1--------------------------http://connectsql.blogspot.com/ |
 |
|
|
loxt
Starting Member
4 Posts |
Posted - 2012-07-24 : 03:33:37
|
| Right, great!! |
 |
|
|
|
|
|
|
|