How to select unique row according to last accessed time
I want to get only distinct rows with their respective AnsId
,
like Qid: 01 have last AnsId: 01
I have following data structure,
Qid Time AnsId
01 2011-09-26 12:55:10 01
02 2011-09-26 12:58:32 03
03 2011-0开发者_如何学Go9-26 12:59:05 02
01 2011-09-26 01:02:10 01
03 2011-09-26 01:30:10 01
02 2011-09-26 01:59:10 02
I have written following query but it returns all the rows:
SELECT DISTINCT Qid, Time, AnsId
FROM table
ORDER BY Time DESC
Then what is missing part in the select query?
You could use row_number()
to find the last answer per Qid
:
select *
from (
select row_number() over (partition by Qid order by Time desc) as rn
, *
from YourTable
) as SubQueryAlias
where rn = 1
The subquery is required because SQL Server doesn't allow row_number
directly in a where
.
declare @T table
(
Qid char(2),
[Time] datetime,
AnsId char(2)
)
insert into @T values
('01', '2011-09-26 12:55:10', '01'),
('02', '2011-09-26 12:58:32', '03'),
('03', '2011-09-26 12:59:05', '02'),
('01', '2011-09-26 01:02:10', '01'),
('03', '2011-09-26 01:30:10', '01'),
('02', '2011-09-26 01:59:10', '02')
select T.Qid,
T.[Time],
T.AnsId
from
(
select T.Qid,
T.[Time],
T.AnsId,
row_number() over(partition by T.Qid order by T.[Time] desc) as rn
from @T as T
) as T
where T.rn = 1
order by T.[Time] desc
Result:
Qid Time AnsId
---- ----------------------- -----
03 2011-09-26 12:59:05.000 02
02 2011-09-26 12:58:32.000 03
01 2011-09-26 12:55:10.000 01
精彩评论