Saroj Shrestha
Saroj Shrestha

Reputation: 21

Get min and max time from date from multiple rows

I have this table with following data.

Uid    date   time
1 2019-07-17   09:00:09
1 2019-07-17  17:30:32
1 2019-07-18   09:30:00
1 2019-07-19   09:14:23
1 2019-07-19   13:14;56
1 2019-07-19   17:34:22

I want to get these into following

1 2019-07-17 09:00:09 17:30:32
1 2019-07-18 09:30:00
1 2019-07-19 09:14:23 17:34:22

I am not good at SQL, so looking for the community help. Thank you

Upvotes: 1

Views: 1324

Answers (3)

juergen d
juergen d

Reputation: 204756

You can do this by grouping first by id and then date to get all unique records. Then you retrieve the min and max time values in the select statement.

SELECT uid, date, min(time), max(time)
FROM your_table
GROUP BY uid, date

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1269603

This is basically aggregation. A handy way to do this uses nullif():

select uid, date, min(time), nullif(max(time), min(time))
from t
group by uid, date

Upvotes: 1

ScaisEdge
ScaisEdge

Reputation: 133360

you could use min() max() and group by check for min() and max() not equal

select uid, date,  min(time) min_time
    , case when min(time) = max(time) then null else max(time) end  max_time
from my_table  
group by  uid, date 

Upvotes: 0

Related Questions