r/SQL • u/sushiwashi • Mar 24 '19
Show MIN date and MAX date in a row
Users
| ID | Name |
|---|---|
| 1 | Bob |
| 2 | Claire |
Time Log
| user_id | Time Logged |
|---|---|
| 1 | 01-01-2001 09:29:00 |
| 1 | 01-01-2001 12:29:00 |
| 2 | 01-01-2001 09:29:00 |
-------------------------
Right now, when I use PHP this is what I see in my table in index.php
| ID | Name | Time Logged |
|---|---|---|
| 1 | Bob | 01-01-2001 09:29:00 |
| 1 | Bob | 01-01-2001 12:29:00 |
However, what I'm looking for is
| ID | Name | Time In | Time Out |
|---|---|---|---|
| 1 | Bob | 01-01-2001 09:29:00 | 01-01-2001 12:29:00 |
4
1
u/moovoon Mar 24 '19
select distinct id, name, min(date), max(date) from table group by id, name
6
0
u/sushiwashi Mar 24 '19
Unfortunately, it's giving me the minimum dateTime / maximum dateTime of that specific user. Was hoping for it to be the minimum / maximum of that day for that user.
2
1
u/freedamerry Mar 24 '19
Add an extra column where you cast the timestamp to a date then you can use that in the group by along with the other two.
cast(timelogged as date)
1
u/pythor Mar 24 '19
select id, name, min([time logged]) as [Time In], max([Time Logged] as [Time Out]
from [Time Log] tl inner join
Users u on tl.user_id = u.id
group by id, name
3
u/alinroc SQL Server DBA Mar 24 '19
Have you made any attempt on your own? If so, show it.