0

I have 100 records from 3 users. I want to show the most recent record from each user. I have the following query:

SELECT *  
FROM Mytable  
WHERE Dateabc = CURRENT DATE 
AND timeabc =  
(
  SELECT MAX(timeabc)
  FROM Mytable
)

It returns the most recent record for everyone, and I need it to return most recent record from every user.

Linger
  • 14,942
  • 23
  • 52
  • 79

3 Answers3

2

Should the solution support both DB2 and mysql?

SELECT * FROM Mytable as x
WHERE Dateabc = CURRENT_DATE 
  AND timeabc = (SELECT MAX( timeabc ) FROM Mytable as y where x.user = y.user)

If it's only DB2 more efficient solutions exists:

SELECT * from (
    SELECT x.*, row_number() over (partition by user order by timeabc desc) as rn 
    FROM Mytable as x
)
WHERE rn = 1
Lennart - Slava Ukraini
  • 6,936
  • 1
  • 20
  • 32
0

I assume somewhere in your table you have a userID...

  select userID, max(timeabc) from mytable group by userID
Twelfth
  • 7,070
  • 3
  • 26
  • 34
0
SELECT *
FROM Mytable as a
WHERE Dateabc = CURRENT_DATE 
AND timeabc =
(
    SELECT MAX( timeabc )
    FROM Mytable as b 
    WHERE a.uId = b.uId
)
Ajk_P
  • 1,874
  • 18
  • 23