繁体   English   中英

postgresql 按日期获取具有不同列值的记录

[英]postgresql to fetch records with different column values by date

表用户

(user_id, vehical_type, created_date)
 1        10            2020-06-01
 2        11            2019-09-09
 1        9             2020-06-02
 1        2             2020-02-01
 2        10            2019-09-06
 2         9            2019-09-11

Result
(user_id, vehical_type, created_date)
 1        10            2020-06-01
 1         9            2020-06-02

查询以获取具有 vehical_type 10,9 的特定用户记录,如果 vehicle_type 10 后跟 vehicle_type 2 by created_date

在上面的结果中,您不应该看到 user_id 2,因为它的 vehicle_type 11(created: 2019-09-09) 存在于它的 vehicle_type 10(2019-09-06) 和 9(2019-09-11) 之间

似乎您想要lead()

select *
from (
    select 
        t.*, 
        lead(vehical_type) over(partition by user_id order by created_date) lead_vehical_type
    from mytable t
) t
where vehical_type in (9, 10) and lead_vehical_type = 2

这会带来vehical_type 9 或 10 的记录,并且相同user_id的下一个vehical_type为 2。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM