gpt4 book ai didi

postgresql - 在行上生成第 n 次出现

转载 作者:行者123 更新时间:2023-11-29 14:30:06 26 4
gpt4 key购买 nike

我希望为每位顾客光顾商店生成第 n 次光顾次数。

使用以下查询:

select customer_id, store_id, date from visits order by date asc;

我得到如图所示的表格:

customer_id | store_id | date
------------------------------------------
1 | 101 | 1st November 2018
2 | 102 | 2nd November 2018
2 | 102 | 3rd November 2018
3 | 103 | 1st November 2018
2 | 102 | 4th November 2018

我想做的是按日期升序排序以附加 nth_visits 列,例如:

customer_id | store_id | date              | nth_visit
-------------------------------------------------------
1 | 101 | 1st November 2018 | 1
2 | 102 | 2nd November 2018 | 1
2 | 102 | 3rd November 2018 | 2
3 | 103 | 1st November 2018 | 1
2 | 102 | 4th November 2018 | 3

有没有办法在 Postgresql 的输出中实现这一点?我尝试过嵌套选择和分组依据,但一切都变成了梨形。

我觉得可能有一个我可以增加的标志,但我找不到这样的东西:

select customer_id, store_id, date, occurance(customer_id, store_id) as nth_visit from visits order by date asc;

最佳答案

您可以使用 window function为此:

select customer_id, 
store_id,
"date",
row_Number() over (partition by customer_id, store_id order by "date") as nth_visit
from visits
order by "date" asc;

关于postgresql - 在行上生成第 n 次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53153279/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com