Teradata 结果中的第 n 个结果
我正在尝试创建一个 Teradata SQL 查询,该查询将返回每个用户的第 n 个按时间顺序排列的访问日期。例如,
user | visit_date
---------------------
a 1/1
b 1/10
c 1/20
a 1/3
a 1/4
b 1/5
c 1/15
b 1/9
> magic_query_for_Second_visit;
user | second
------------------
a 1/3
b 1/9
c 1/20
我尝试了类似下面的内容,但 Teradata 尖叫道“WHERE
子句中不允许使用有序分析函数。”我拉头发有一段时间了,但没有取得太大进展。有人见过这个吗?
select user,
row_number() over (partition by user order by visit_date desc) as rnum
from visitstable
where rnum = 2
如果我排除 where
那么我的结果看起来很有希望......我只是无法提取我需要的东西!
user | visit_date | rnum
---------------------------
a 1/1 1
a 1/3 2
a 1/4 3
b 1/5 1
b 1/9 2
b 1/10 3
c 1/15 1
c 1/20 2
预先感谢您的帮助!
I'm trying to make a Teradata SQL query that will return the n-th chronological visit date for each user. E.g.,
user | visit_date
---------------------
a 1/1
b 1/10
c 1/20
a 1/3
a 1/4
b 1/5
c 1/15
b 1/9
> magic_query_for_Second_visit;
user | second
------------------
a 1/3
b 1/9
c 1/20
I tried something like the below, but Teradata shrieked that "Ordered analytical functions are not allowed in WHERE
clause." I've pulled my hair for a while but am not making much progress. Anyone seen this?
select user,
row_number() over (partition by user order by visit_date desc) as rnum
from visitstable
where rnum = 2
If I exclude the where
then my result looks promising... I just can't extract what I need!
user | visit_date | rnum
---------------------------
a 1/1 1
a 1/3 2
a 1/4 3
b 1/5 1
b 1/9 2
b 1/10 3
c 1/15 1
c 1/20 2
Thanks in advance for the help!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我从您的评论中看到,您不一定想要依赖 Teradata 特定的
QUALIFY
。以下是基于另一小伙子答案的一种便携式解决方案(因为许多 RDBMS 现在支持 CTE):I see from your comment that you don't necessarily want to rely on the Teradata-specific
QUALIFY
. The following is a sort-of portable solution (as many RDBMSes are now supporting CTEs) based on another chap's answer:哦,天哪,我应该查看文档。仅供参考,看起来
qualify
可以让您指定有序的分析约束。然而,qualify
不是 ANSI,所以我仍在为便携式解决方案提供积分...我可以做:
...并获得...
添加书签! :)
Oh, heaven forbid I should look in the documentation. FYI, it looks like
qualify
lets you specify ordered analytic constraints. However,qualify
isn't ANSI, so I'm still handing out points for a portable solution...I can do:
...and get...
Bookmark it! :)
您使用什么版本的 SQL?它看起来像 MS SQL Server 的更高版本,因此请尝试使用像这样的“公用表表达式”...
其中 cte 为 (
选择用户,
row_number() over (按用户顺序按访问日期 desc 分区) as rnum
来自可访问表
)
从 cte 中选择 *
其中 rnum = 2
语法
可能需要一些调整,但这是一般原则。
What version of SQL are you using? It looks like a later version of MS SQL Server, so try using a "common table expression" like this...
with cte as (
select user,
row_number() over (partition by user order by visit_date desc) as rnum
from visitstable
)
select * from cte
where rnum = 2
The syntax might require a little tweaking, but that's the general principal.