根据创建的时间戳消除行

时间:2018-05-22 13:51:01

标签: sql postgresql greatest-n-per-group

我想帮助将此表与不同的uuids用于相同的电子邮件,并且只获得带有min(时间戳)的行,从而消除其他的

示例数据:

UUID   email       created_timestamp  
  1    a@g.com        2017-05-01
  2    a@g.com        2018-05-01
  3    a@g.com        2018-05-20
  4    b@g.com        2017-04-01
  5    b@g.com        2017-06-01

预期产出:

UUID   email       created_timestamp 
  1    a@g.com        2017-05-01
  4    b@g.com        2017-04-01

我曾尝试使用group by,但它让我按UUID分组,在这种情况下没有意义

3 个答案:

答案 0 :(得分:0)

function UserModel(data) {
    var _self = this;
    this.id = ko.observable(0);
    this.Email = ko.observable();
    this.FirstName = ko.observable();
    this.LastName = ko.observable();
    this.UserID = ko.observable();

    if (data != null) {
        _self.id(data.ID);
        _self.Email(data.Email);
        _self.FirstName(data.FirstName);
        _self.LastName(data.LastName);
        _self.UserID(data.UserID);
    }


}

答案 1 :(得分:0)

您可以将LIMIT子句与subquery

一起使用
select t.* 
from table t
where UUID = (select UUID
              from table t1
              where t1.email = t.email
              order by created_timestamp asc
              limit 1
             );

但是,如果created_timestamp没有重复,那么您可以将其表达为:

select t.* 
from table t
where created_timestamp = (select min(created_timestamp)
                           from table t1
                           where t1.email = t.email
                           );

答案 2 :(得分:0)

我认为Postgres的最佳方式是distinct on

select distinct on (email) t.*
from t
order by email, created_timestamp desc;

特别是,对于(email, created_timestamp)的索引,这应该是最快的解决方案。