简体   繁体   中英

SQL query to group by and order by timestamp

Hey guys, I've tried to get this right but I can't, maybe you can point me in the right direction

I have 3 columns, 'url_id', 'timestamp' and 'o'. I need to group by 'url_id' and sort by the most current timestamp.

table "example"

timestamp | url_id   |    o
----------------------------
2000      | 1        |   50
2007      | 1        |   70
2011      | 1        |   90
2001      | 2        |   20
2006      | 2        |   50
2009      | 2        |   40
2011      | 2        |   10

'o' is the value at the end I want. I was trying to do this with a subquery but kept getting the oldest value (tried order by, and had no luck).

What am I doing wrong? Is what I'm looking for actually require a subquery?

SELECT url_id
     , MAX(timestamp) AS currentTS
  FROM yourTable
  GROUP BY url_id
  ORDER BY currentTS DESC

Aftre you last explanation, I think you need to JOIN the above query to your original table, like this:

SELECT y.timestamp
     , y.url_id
     , y.o
FROM yourTable y
JOIN 
    ( SELECT url_id
           , MAX(timestamp) AS currentTS
      FROM yourTable
      GROUP BY url_id
    ) AS grp
  ON grp.url_id = y.url_id
    AND grp.currentTS = y.timestamp
ORDER BY y.timestamp DESC

Note: if there are two (or more) rows with same url_id and same timestamp, they'll both (or all) appear at the results.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM