我有多个用户,每个用户需要10个问题并留下一些时间戳。我理想的做法是找到第n个用户的完整时间,其中n由时间戳的升序而不是用户ID确定。
这不起作用,但为了让你感受到我的需要,如果可以的话,我将非常高兴:
SELECT <N-TH> MAX(u.time) AS maxTime FROM Users u
Group BY u.userId ORDER BY maxTime
有什么想法?现在我正在运行
SELECT MAX(u.time) AS maxTime FROM Users u
Group BY u.userId ORDER BY maxTime
将结果作为数组获取,然后找到第n个条目。
答案 0 :(得分:0)
许多可能的方法,但只是袖口...可以使用CTE或子查询。 尝试
SELECT MAX([maxTime]) AS [LastEntry] FROM (
SELECT MAX(u.time) AS maxTime,u.userId
FROM Users u
GROUP BY u.userId,u.time) t
好的,试试这个......
WITH CTE ([maxTime], [userId ]) AS (
SELECT MAX([time]) AS [maxTime],
[userId]
FROM Users
GROUP BY [userId])
SELECT MAX([maxTime]) AS [maxTime]
FROM CTE;
HTH
戴夫
答案 1 :(得分:0)
您是否尝试过使用ROW_NUMBER()
功能
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
其中NthNumber
是排名编号。
答案 2 :(得分:0)
GROUP BY
UserId,并根据ROW_NUMBER
应用max(u.time)
来创建一个排名伪列,然后您可以对其进行过滤
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
答案 3 :(得分:0)
按照最长时间排序前10行:
SELECT TOP 10 userId, MAX(time) AS maxtime
FROM Users
GROUP BY userId
ORDER BY maxtime ASC
然后只需颠倒顺序并占据最上一行:
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;