[英]how to pick the latest data in postgresql
i want to query my db with the latest record on file.我想用文件上的最新记录查询我的数据库。 When I try this:
当我尝试这个时:
select distinct(ts) from my_table
I get two dates:我得到两个日期:
2020-03-10 22:54:08
2020-03-10 22:29:57
my db schema:我的数据库架构:
Create table my_table
(
uuid text NULL,
portfolio_family_id bigint NULL,
ticker text NULL,
size double precision NULL,
secid bigint NULL,
portfolio_name_id bigint NULL,
ts timestamp NOT NULL DEFAULT now()
);
you can have multiple repetitive uuids in the uuid column.您可以在 uuid 列中有多个重复的 uuid。 I would like to get all the rows where ts is the latest data.
我想获取 ts 是最新数据的所有行。 How would i query this?
我将如何查询?
select to_char(ts,'YYYY-MM-DD HH24:MI:SS') ts2 from my_table mt
inner join (select to_char(max(ts),'YYYY-MM-DD HH24:MI:SS') t2 from
my_table) c2 on c2.t2 = mt.ts2
I get error: column ts2 doesn't exist.我收到错误:列 ts2 不存在。 Hint: Perhaps you mean to reference mt: ts?
提示:也许您的意思是引用 mt: ts?
I want all records pertaining to this date: 2020-03-10 22:29:57我想要与此日期有关的所有记录:2020-03-10 22:29:57
If you want the latest row per uuid
, then:如果您想要每个
uuid
的最新行,则:
select distinct on (uuid) *
from mytable
order by uuid, ts desc
If you want all rows that correspond to the latest date available in the table, then:如果您希望与表中可用的最新日期相对应的所有行,则:
select t.*
from mytable t
where t.ts = (select max(t1.ts) from mytable t1)
You can get the same result with window functions:您可以使用窗口函数获得相同的结果:
select (s.t).*
from (select t, rank() over(order by ts desc) rn from mytable t) s
where rn = 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.