0

I'm having table with two columns namely hostname and timestamp. Host name will be having many duplicates values as mentioned below. I need to get the timestamp of the last entry of particular duplicated value .In this case,There are duplicate values for both Server AB and CD.but i need to find the duplicate value for Hostname=AB. IN real time this table will be containing many duplicates for hostname.

|hostname |timestamp|
|:........|---------:|
|AB       |14Aug2021 11:12|
|BC       |15Aug2021 11:12|
|CD       |16Aug2021 11:12|
|CD      |22Aug2021 11:12|
|AB      |25Aug2021 11:12|
|CD      |26Aug2021 11:12|

In the above table I need to get the latest entry of time stamp for hostname=AB

  • Shouldn't `(CD, '26Aug2021 11:12')` be the correct record, as `CD` is duplicate, and this is the most recent such duplicate record? – Tim Biegeleisen Oct 22 '21 at 05:15

3 Answers3

0

You could try a LIMIT query here:

SELECT hostname, timestamp
FROM yourTable t1
WHERE EXISTS (SELECT 1 FROM yourTable t2
              WHERE t2.hostname = t1.hostname AND
                    t2.timestamp <> t1.timestamp)
ORDER BY timestamp DESC
LIMIT 1;
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360
0

That should be as simple as

SELECT max(timestamp) FROM tab WHERE hostname = 'AB';

The aggregate max will return the maximal timestamp from all rows matching the WHERE condition.

Laurenz Albe
  • 209,280
  • 17
  • 206
  • 263
0

distinct on is what you need. Please note the order by clause.

select distinct on (hostname) *
from the_table 
where hostname = 'AB'
order by hostname, "timestamp" desc;

This particular illustration returns the latest record for hostname 'AB'. You can use other conditions as you wish or no where at all which will produce the latest records for all hostnames. If you need just the timestamp for one hostname only then the answer of @LaurenzAlbe should be better.

Stefanov.sm
  • 11,215
  • 2
  • 21
  • 21