【问题标题】:SQL Query for timestampSQL查询时间戳
【发布时间】:2015-12-09 17:36:11
【问题描述】:

我有以下表格

CREATE TABLE Customer
    ( `Name` varchar(7), `Address` varchar(55), `City` varchar(15),`Contact` int,`timestamp` int)
;

INSERT INTO Customer
    (`Name`,`Address`, `City`, `Contact`,`timestamp`)
VALUES
    ('Jack','New City','LA',79878458,456125),
    ('Joseph','New Lane23','LA',87458458,794865),
   ('Rosy','Old City','Paris',79878458,215125),
   ('Maria','New City','LA',79878458,699125),
   ('Jack','New City','LA',79878458,456125),
   ('Rosy','Old City','Paris',79878458,845125),
   ('Jack','New Main Street','New York',79878458,555525),
   ('Joseph','Near Bank','SAn Francisco',79878458,984521)

;

我想获取所有具有最高时间戳且不重复的客户记录。

【问题讨论】:

    标签: android sql sqlite android-sql


    【解决方案1】:

    试试下面的。

    select name,max(timestamp),Address,City,Contact from Customer group by name 
    

    【讨论】:

      【解决方案2】:

      我想获取所有具有最高时间戳的客户记录 重复。

      使用DISTINCT 运算符和ORDER BY 子句类似

      select distinct `Name`,`Address`, `City`, `Contact`,`timestamp`
      from customer
      order by `timestamp` desc;
      

      在这种情况下,您可以使用JOIN 查询

      select t1.*
      from customer t1 join
      (select Name, max(`timestamp`) as maxstamp
       from customer
       group by Name) xx 
       on t1.Name = xx.Name
       and t1.`timestamp` = xx.maxstamp;
      

      【讨论】:

      • 但是想显示具有最高时间戳的同名记录
      【解决方案3】:

      我正在将 Customer 表与自身连接,连接子句上的条件 c1.timestamp<c2.timestampc2.timestamp IS NULL 结合 将确保只返回每个人的最新记录。我输入了DISTINCT,因为在您的示例数据中,Jack 的两条记录具有相同的时间戳:

      SELECT DISTINCT
        c1.*
      FROM
        Customer c1 LEFT JOIN Customer c2
        ON c1.Name=c2.Name
           AND c1.Contact=c2.Contact -- you might want to remove this
           AND c1.timestamp<c2.timestamp
      WHERE
        c2.timestamp IS NULL
      ORDER BY
        Name, Address
      

      请看小提琴here

      【讨论】:

      • select t1.* from customer t1 join (select Name, max(timestamp) as maxstamp from customer group by Name) xx on t1.Name = xx.Name and t1.timestamp = xx.maxstamp;
      • 但如果任何行重复/重复,它也会重复显示该行
      • @LalitJadiya 使用子查询是一种替代解决方案,但我更喜欢使用 LEFT JOIN ...是的,如果您有两个具有不同详细信息但最大时间戳相同的联系人,他们将被复制...但是在这种情况下你想返回哪条记录?
      【解决方案4】:

      试试这个:

      SELECT * FROM `customer` 
      group by name,Address,City,Contact,timestamp
      order by timestamp desc
      

      【讨论】:

      • 但是想显示具有最高时间戳的同名记录
      • 如果你的数据库是 mysql,你应该试试这个:"SELECT Name,max(timestamp) as timestamp FROM customer group by Name order by Name asc,timestamp asc"
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多