我正在使用sql-server 2005
嗨,我有带有userID和registrationDate的Users表。我希望在第一个日期为x而其他行为x + 10行时选择两个registrationDates之间的最短时间段。我不介意游标,因为我会偶尔运行此查询。
我将再次解释,我需要10个用户注册之间的最短时间,以了解每个特定时间的注册边界是什么。
感谢
答案 0 :(得分:1)
如果您使用的是SQL Server 2005或更高版本,请尝试此查询:
WITH T1 AS (
SELECT
userID,
registrationDate,
ROW_NUMBER() OVER (ORDER BY registrationDate) AS rn
FROM Users
), T3 AS (
SELECT
T1.registrationDate AS interval_start,
T2.registrationDate AS interval_end,
T1.registrationDate - T2.registrationDate AS diff
FROM T1
JOIN T1 T2
ON T1.rn = T2.rn + 5
)
SELECT TOP 1 interval_start, interval_end
FROM T3
ORDER BY diff