7

我有一个包含重复行和三次行的表 - 如何选择重复但具有最新时间戳的行以及未重复行?

 -------------------------------------
| pk_id | user_id | some_timestamp    |
|-------------------------------------|
| 1     | 123     | 10-Jun-12 14.30   |
| 2     | 123     | 19-Jun-12 21.50   |
| 3     | 567     | 10-Jun-12 09.23   |
| 4     | 567     | 12-Jun-12 09.45   |
| 5     | 567     | 13-Jun-12 08.40   |
| 6     | 890     | 13-Jun-12 08.44   |
 -------------------------------------

所以我最终得到:

 -------------------------------------
| pk_id | user_id | some_timestamp    |
|-------------------------------------|
| 2     | 123     | 19-Jun-12 21.50   |
| 5     | 567     | 13-Jun-12 08.40   |
| 6     | 890     | 13-Jun-12 08.44   |
 -------------------------------------
4

5 回答 5

8
SELECT * FROM ( 
SELECT pk_id, 
       user_id, 
       some_timestamp, 
       ROW_NUMBER() OVER (PARTITION BY user_id ORDER BY some_timestamp DESC) col 
FROM table) x  
WHERE x.col = 1
于 2012-12-31T10:01:38.837 回答
4

试试这个

select * from table 
where some_timestamp 
   in (select max(some_timestamp)
       from table group by user_id)
于 2012-12-31T09:44:43.400 回答
2

试试这个,我做了一个返回正确数据集的 SQLFIDDLE

SELECT * FROM YourTable AS T1
INNER JOIN
( SELECT user_id , MAX(some_timestamp) AS some_timestamp FROM YourTable 
GROUP BY user_id
) AS T2
ON T1.User_Id = T2.User_Id AND T1.some_timestamp = T2.some_timestamp
ORDER BY 1

http://sqlfiddle.com/#!6/f7bba/6

于 2012-12-31T10:01:26.533 回答
1
select YourTable.*
from
  YourTable JOIN
  (select User_Id, Max(Some_Timestamp) as Mx
   from YourTable
   group by User_Id) Mx
  on YourTable.User_Id=Mx.User_Id
   and YourTable.Some_Timestamp=Mx.Mx
于 2012-12-31T09:56:40.043 回答
1

试试这个:

select * from my_table
where (user_id, some_timestamp) IN (select user_id, max(some_timestamp) from my_table group by user_id);
于 2012-12-31T09:59:33.133 回答