在行上生成第n次出现

时间:2018-11-05 11:13:24

标签: postgresql

我希望为每位顾客访问商店产生第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和group by,但是一切都变得有点像梨子了。

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

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

1 个答案:

答案 0 :(得分:2)

您可以使用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;