0

I have number of users, each taking 10 questions and leave some time stamps. What I ideally want to do is to find the complete time of the n-th user where n is determined by the ascending order of time stamps, not the user ids.

This will not work, but to give you a feel of what I need I would be very happy if this could run:

SELECT <N-TH> MAX(u.time) AS maxTime FROM Users u
Group BY u.userId   ORDER BY maxTime

Any thoughts? right now I am running

SELECT MAX(u.time) AS maxTime FROM Users u
Group BY u.userId   ORDER BY maxTime

get the result as array and then find the n-th entry.

fancyPants
  • 50,732
  • 33
  • 89
  • 96
AKG
  • 45
  • 6

4 Answers4

0

Many possible ways but just off cuff...could use CTEs or subquery. Try

SELECT MAX([maxTime]) AS [LastEntry] FROM (
    SELECT MAX(u.time) AS maxTime,u.userId 
    FROM Users u 
    GROUP BY u.userId,u.time) t

OK, try this...

WITH CTE ([maxTime], [userId ]) AS (
    SELECT MAX([time]) AS [maxTime],
        [userId]
    FROM Users
    GROUP BY [userId])
    SELECT MAX([maxTime]) AS [maxTime]
    FROM CTE;

HTH

Dave

Dave
  • 740
  • 1
  • 6
  • 17
0

Have you tried using ROW_NUMBER() function

SELECT * FROM
(
SELECT ROW_NUMBER() OVER (ORDER BY maxTime) as RowNum, MAX(u.time) AS maxTime FROM Users u
Group BY u.userId
) A
WHERE RowNum = NthNumber
ORDER BY maxTime

where NthNumber is the ranking number.

Edper
  • 9,144
  • 1
  • 27
  • 46
  • Unfortunately, order by cannot be used in sub-queries. – AKG Jun 07 '13 at 14:44
  • You're right @user1288502 actually I just forget to remove it. But it could now be sorted if it is used outside which my query already had. – Edper Jun 07 '13 at 15:32
0

GROUP BY UserId, and apply ROW_NUMBER based on max(u.time) to create a ranking pseudo-column that you can then filter on

select min_utime, max_utime, userId from (
select min(u.time) min_utime, max(u.time) max_utime, u.userId,
row_number() over (order by max(u.time) asc) as ranker
from Users u
group by u.userId
) Z  where ranker  = @n
iruvar
  • 22,736
  • 7
  • 53
  • 82
0

Get the first 10 rows as sorted by the maximum time:

SELECT TOP 10 userId, MAX(time) AS maxtime
FROM Users
GROUP BY userId
ORDER BY maxtime ASC

Then just reverse the order and take the top row:

SELECT TOP 1 *
FROM (
  SELECT TOP 10 userId, MAX(time) AS maxtime
  FROM Users
  GROUP BY userId
  ORDER BY maxtime ASC
) s
ORDER BY maxtime DESC;
Andriy M
  • 76,112
  • 17
  • 94
  • 154