开发者

How to extract the latest rows

I have a table like this:

Table A
Date    Time    ID  Ref
110217  91703   A001    A1100056
110217  91703   A001    A1100057
110217  91703   A001    A1100058
110217  91703   A001    A1100059
110217  132440  A001    A1100057
110217  132440  A001    A1100058
110217  132440  A001    A1100060
110217  91703   B001    B1100048
110217  9开发者_如何学JAVA1703   B001    B1100049
110217  132440  B001    B1100049
110217  132440  B001    B1100050

I wish to have the latest data only & the final result should look like this using SQL:

Date    Time    ID  Ref
110217  132440  A001    A1100057
110217  132440  A001    A1100058
110217  132440  A001    A1100060
110217  132440  B001    B1100049
110217  132440  B001    B1100050

(3 records all with the same "latest" time)

The database will self-update by itself at certain time. The problem is: I do not know the exact time, hence I do not know which record is the latest.


This works in SQL Server:

SELECT TOP 1 WITH TIES *
FROM TableA
ORDER BY Date DESC, Time DESC

And this solution is probably server-independent:

SELECT a.*
  FROM TableA a
  JOIN (
       SELECT d.MaxDate, MAX(t.Time) AS MaxTime
         FROM TableA t
         JOIN (
              SELECT MAX(Date) AS MaxDate
                FROM TableA
              ) d
           ON t.Date = d.MaxDate
        GROUP BY d.MaxDate
       ) m
    ON a.Date = m.MaxDate AND a.Time = m.MaxTime


SELECT * FROM table ORDER BY date DESC, time DESC LIMIT 1;

Will give you the latest row in MySql.


Which database are you using? You can actually concat the two columns after converting them to a date and time format, and then order by date. All this can be achieved in query.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜