Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/68.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在PostgreSQL中为每个客户选择最后两条记录_Sql_Postgresql - Fatal编程技术网

在PostgreSQL中为每个客户选择最后两条记录

在PostgreSQL中为每个客户选择最后两条记录,sql,postgresql,Sql,Postgresql,你能告诉我以下场景的查询吗? 我在表访问日志中有以下列: 客户可能多次访问该服务。但是我只需要列出每个客户id的最后两个记录。按照这些方法应该可以: select * from access_log a1 where 2 > (select count(*) from access_log a2 where a1.customer_id = a2.customer_id and a1.accessed_time < a2.accessed_

你能告诉我以下场景的查询吗? 我在表访问日志中有以下列:


客户可能多次访问该服务。但是我只需要列出每个客户id的最后两个记录。

按照这些方法应该可以:

select * from access_log a1
where 2 > (select count(*) from access_log a2
           where a1.customer_id = a2.customer_id
           and a1.accessed_time < a2.accessed_time)
这意味着:获取同一客户的所有日志,其中存在0或1个其他访问日志,且访问时间较晚。请确保在相关列上有适当的索引。

再次提醒您:

select customer_id, service_name, accessed_time
from (
    select customer_id, service_name, accessed_time,
           rank() over (partition by customer_id order by accessed_time desc) as rank
    from access_log
) dt
where dt.rank <= 2
上述查询产生:

 customer_id | service_name |    accessed_time    
-------------+--------------+---------------------
           1 | three        | 2011-01-03 00:00:00
           1 | two          | 2011-01-02 00:00:00
           2 | three        | 2011-05-03 00:00:00
           2 | one          | 2011-04-01 00:00:00

美好的可能需要按客户id、服务名称进行分区。OP对他们问题的表述方式,似乎这些统计数据应该是基于每个客户和每个服务的…?@Lukas:OP确实说每个客户id只有最后两条记录,所以我不认为服务名称进入其中,除非作为显示的内容。我看看能否得到澄清。嗯。。。我被可能访问该服务的in弄糊涂了。您是在寻找最后两个,即每个客户id的最近两个,不管服务名称是什么,还是服务名称涉及到了什么?是的。。每个customer\u id有两个最新记录,更不用说service\u name和WHERE子句的用法了。从未想过类似的事情。@bos:谢谢。尽管如此,我认为mu太短了,它的解决方案可能会优于最佳窗口前建议。
=> select * from access_log order by customer_id, accessed_time;
 customer_id | service_name |    accessed_time    
-------------+--------------+---------------------
           1 | one          | 2011-01-01 00:00:00
           1 | two          | 2011-01-02 00:00:00
           1 | three        | 2011-01-03 00:00:00
           2 | two          | 2011-01-02 00:00:00
           2 | one          | 2011-04-01 00:00:00
           2 | three        | 2011-05-03 00:00:00
 customer_id | service_name |    accessed_time    
-------------+--------------+---------------------
           1 | three        | 2011-01-03 00:00:00
           1 | two          | 2011-01-02 00:00:00
           2 | three        | 2011-05-03 00:00:00
           2 | one          | 2011-04-01 00:00:00