S
S
sbh2020-05-03 05:10:12
MySQL
sbh, 2020-05-03 05:10:12

How to select unique records with the maximum value?

Table1

ID   ClientID    StartTS                               FinishTS
1     2233        2020-05-01 12:02:01                  2020-05-01 13:02:03
2     2233        2020-05-01 12:02:01                  2020-05-01 14:02:03
3     5212        2020-05-01 10:01:32                  2020-05-01 11:01:11
4     2233        2020-05-02 08:02:11                  2020-05-02 09:01:11
5     2233        2020-05-02 08:02:11                  2020-05-02 10:01:12
6     5212        2020-05-01 10:01:32                  2020-05-01 12:01:11


It is necessary to select all records with a unique StartTS field and the maximum of those selected for each FinishTS record.
That is, in this example, the correct query result will be:
ID   ClientID    StartTS                               FinishTS
2     2233        2020-05-01 12:02:01                  2020-05-01 14:02:03
5     2233        2020-05-02 08:02:11                  2020-05-02 10:01:12
6     5212        2020-05-01 10:01:32                  2020-05-01 12:01:11

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Dimonchik, 2020-05-03
@dimonchik2013

SELECT StartTS FROM table t1 WHERE  FinishTS=(SELECT MAX(t2.FinishTS)  FROM table t2  WHERE t1.StartTS = t2.StartTS)

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question