SQL 选择间隔一小时的记录
我正在尝试编写一个查询,该查询返回具有唯一人员 ID、地点 ID 的值,并且仅返回 60 分钟内第一次出现的访问。
这接近我需要的..
SELECT * FROM
(
SELECT
RANK() OVER (PARTITION BY A.PersonId, A.PlaceId,
DATEDIFF(hh, A.Visit_Datetime, GETDATE()) ORDER BY A.Visit_Datetime) AS RNK,
A.RecordId,
A.PersonId,
A.PlaceId
FROM
Table A
) A
WHERE
A.Rnk = 1
问题是,如果一个人在上午 10:50 访问,然后在上午 11:10 创建第二条记录,则两条记录的排名均为 1。我需要的是对这些记录进行排名按人物、地点和 60 分钟范围。
我希望这是有道理的。感谢您的帮助。
I am trying to write a query that returns values with a unique person id, place id, and only the first occurrance of the visit within 60 minutes.
Here is close to what I need..
SELECT * FROM
(
SELECT
RANK() OVER (PARTITION BY A.PersonId, A.PlaceId,
DATEDIFF(hh, A.Visit_Datetime, GETDATE()) ORDER BY A.Visit_Datetime) AS RNK,
A.RecordId,
A.PersonId,
A.PlaceId
FROM
Table A
) A
WHERE
A.Rnk = 1
The problem with is that if a person visits at 10:50AM and then a second record is created at 11:10 AM, both records are Ranked as 1. What I need is to rank these records by person, place, and 60 minute range.
I hope this makes sense. Thanks for the help.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
试试这个
Try this
目前,您正在对由当前时间确定的固定时间段进行分组。
你想要一个移动的时间段。这不能基于当前日期或 0 这样的文字。
这意味着您需要对所有可能时间的小时段进行分组。幸运的是,您不需要全部计算。
相反,将每次访问时间的小时段分组。即 10:50 与 10:50 至 11:50 之间的所有访问进行分组,以及 11:10 与 11:10 至 12:10 之间的访问进行分组。
这将产生重叠的组,类似于具有多个排名 1。
B 连接到所有出现的情况,但您想要第一个出现的情况。
将出现的事件分组在一起并使用 min 来获取第一个。
像这样的内容:
这应该为您提供每个记录、人员、地点的访问时间。访问时间实际上是任意长度的,但每次发生的时间间隔都在 60 分钟之内。这听起来像是您想要做的事情。
Currently you are grouping fixed hour periods, determined by the current time.
You want a moving hour period. This can't be based on the current date or a literal like 0.
This implies you would need to group the hour period for all possible times. Fortunately you don't need to calculate them all.
Instead group the hour period for each visit time. i.e 10:50 is grouped with all visits between 10:50 and 11:50 and 11:10 with visits between 11:10 and 12:10
This will produce overlapping groups, similar to having multiple rank of 1.
B is joined to all occurrences but you want the first occurrence.
Group the occurrences together and use min to get the first one.
Something like this:
This should give you visit time for each Record, Person, Place. The visit period is actually of any length but each occurrence is within 60 minutes of another. This sounds like what you where trying to do.