计算客户在SQL中最后两个订单中的订单数量少于当前订单值的订单数?
认为我有一张桌子
客户 | 日 | 量 |
---|---|---|
A | 4 | 96 |
A | 22 | 63 |
A | 32 | 19 |
A | 50 | 27 |
A | 57 | 99 |
A | 69 | 97 |
72 93 B | 82 | 22 22 |
B | 2 | 22 |
B | 87 | 64 |
C 22 60 C | 22 | 60 |
C | 30 | 2 23 |
2 22 | 48 | 74 |
C | 49 | 68 |
C | 55 | 11 |
C | 85 | 79 |
我需要计算每个客户的订单数量 小于他过去两个订单的订单值订单,即
客户 | 节 | 数量 | 计数 |
---|---|---|---|
A | 4 | 96 | 0 |
A | 22 | 63 | 0 |
A | 32 | 19 | 0 |
A | 50 | 27 | 1 |
A | 57 | 99 | 2 |
A | 72 | 93 | 1 |
B | 69 | 97 | 0 |
B | 82 | 22 | 0 |
B | 87 | 64 | 1 |
C | 22 | 60 | 0 |
C | 30 | 2 23 | 0 |
C | 48 | 74 | 2 |
C | 49 | 68 | 1 |
C | 55 | 11 | 0 |
C | 85 | 79 | 2 |
Consider that I have a table
Customer | Day | Amount |
---|---|---|
A | 4 | 96 |
A | 22 | 63 |
A | 32 | 19 |
A | 50 | 27 |
A | 57 | 99 |
A | 72 | 93 |
B | 69 | 97 |
B | 82 | 22 |
B | 87 | 64 |
C | 22 | 60 |
C | 30 | 22 |
C | 48 | 74 |
C | 49 | 68 |
C | 55 | 11 |
C | 85 | 79 |
I need to calculate the number of orders for every customer whose value is less than the order value of the present order among his past two orders, i.e
Customer | Day | Amount | Count |
---|---|---|---|
A | 4 | 96 | 0 |
A | 22 | 63 | 0 |
A | 32 | 19 | 0 |
A | 50 | 27 | 1 |
A | 57 | 99 | 2 |
A | 72 | 93 | 1 |
B | 69 | 97 | 0 |
B | 82 | 22 | 0 |
B | 87 | 64 | 1 |
C | 22 | 60 | 0 |
C | 30 | 22 | 0 |
C | 48 | 74 | 2 |
C | 49 | 68 | 1 |
C | 55 | 11 | 0 |
C | 85 | 79 | 2 |
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于您仅是
2行,因此您可以预先计算
lag
值,并利用case
语句来生成所需的逻辑。上更具动态和灵活性
它在本质
否则,如果您希望
Since you are only
PRECEEDING
2 ROWS , you can pre-compute theLAG
values and utilise aCASE
statement to generate the required logic.Else if you want it to be more dynamic and flexible in nature you can utilise Shubham Sharma's answer
Data Preparation
SparkSQL
我们可以在否则的情况下做到这一点
We can do this with when otherwise and lag
让我们使用
coce> collect_list_list
代码>窗口
收集与过去两个订单相对应的金额,然后gentrage> gentreg> gentreg
计算列表中的值在当前行中小于金额
Let us use
collect_list
overWindow
to collect the amounts corresponding to past two orders, thenaggregate
to count the values in list which are less thanAmount
in current row