在SQL Server中按段中的客户交易排名

发布于 2025-02-13 04:28:49 字数 2759 浏览 0 评论 0原文

我有以下,其中包含客户的交易详细信息。

tranactaction Dateculting ind
1/27/20221
1/29/20221
2/27/20221
3/27/20221
3/29/20221
3/31/20221
4/2/20221
4/4/4/202222221
4/6/20221

在该表中连续交易发生在每两天被视为一个细分市场中。 例如, 1月27日至1月29日之间的交易被认为是段1& 3月29日和4月6日之间的交易被认为是段2。我需要按日期顺序对每段的交易进行排名。如果默认情况下,交易不属于任何细分市场,则排名为1。预期输出为低于。

细分等级tranactaction datecusitiverid
11/27/20221
21/29/20221
12/27/20221
1 13/27/20221
23/29/20221
33/31/20221
4 4 4/ 4/4/ 2/20221
54/4/20221
64/6/20221

有人可以指导如何在T-SQL中实现这一目标吗?

I have below table which has customer's transaction details.

Tranactaction dateCustomerID
1/27/20221
1/29/20221
2/27/20221
3/27/20221
3/29/20221
3/31/20221
4/2/20221
4/4/20221
4/6/20221

In this table consecutive transactions occurred in every two days considered as a segment.
For example, Transactions between Jan 27th and Jan 29th considered as segment 1 & Transactions between Mar 29th and Apr 6th considered as Segment 2. I need to rank the transactions per segment with date order. If a transaction not fall under any segment by default the rank is 1. Expected output is below.

Segment RankTranactaction dateCustomerID
11/27/20221
21/29/20221
12/27/20221
13/27/20221
23/29/20221
33/31/20221
44/2/20221
54/4/20221
64/6/20221

Can somebody guide how to achieve this in T-sql?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

北城挽邺 2025-02-20 04:28:49

使用 ()检查transdate的更改,即在2天之内并组合在一起(作为一个细分)。 After that use row_number() to generate the required sequence

with 
cte as
(
    select *,
           g = case when datediff(day,
                                  lag(t.TransDate) over (order by t.TransDate),
                                  t.TransDate
                                  ) <= 2
                    then 0
                    else 1
                    end
    from   tbl t
),
cte2 as
(
    select *, grp = sum(g) over (order by TransDate)
    from cte
)
select *, row_number() over (partition by grp order by TransDate)
from   cte2 

Using lag() to check for change in TransDate that is within 2 days and groups together (as a segment). After that use row_number() to generate the required sequence

with 
cte as
(
    select *,
           g = case when datediff(day,
                                  lag(t.TransDate) over (order by t.TransDate),
                                  t.TransDate
                                  ) <= 2
                    then 0
                    else 1
                    end
    from   tbl t
),
cte2 as
(
    select *, grp = sum(g) over (order by TransDate)
    from cte
)
select *, row_number() over (partition by grp order by TransDate)
from   cte2 

db<>fiddle demo

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文