从其他列的每个唯一属性中选择列的最后统计信息

时间:2016-06-22 13:37:59

标签: sql postgresql

我有一个很大的问题。 我需要检查每个唯一ID的列平衡的最后(实际)统计数据。表格如下:

time_created         ID  balance 
2014-11-12 17:54:24  76  150 
2014-11-12 17:54:41  76  280 
2014-11-14 18:13:28  15  390 
2014-11-14 18:14:09  26  760 
2014-11-14 18:14:53  98  89 
2014-11-16 18:08:00  76  13 
...                  ...

我需要做些什么来解决它?

谢谢你!

1 个答案:

答案 0 :(得分:1)

自我加入版本。带group by的子查询返回每个id及其最新time_created值。

select t1.*
from tablename t1
  join (select id, max(time_created) as time_created
        from tablename
        group by id) t2
  on t1.id = t2.id and t1.time_created = t2.time_created

IN版本:

select *
from tablename
where (id, time_created) IN (select id, max(time_created)
                             from tablename
                             group by id)

NOT EXISTS版本:

select *
from tablename t1
where not exists (select * from tablename t2
                  where t2.id = t1.id
                    and t2.time_created > t1.time_created)