0

This is my table looked like:

Employee_Number       |       DateTime
00000001              |       2014/01/14  09:20
00000001              |       2014/01/14  12:35
00000001              |       2014/01/14  13:35
00000002              |       2014/01/14  09:20
00000001              |       2014/01/14  22:49
00000001              |       2014/01/15  09:35
00000001              |       2014/01/15  10:35
00000001              |       2014/01/15  17:35
00000002              |       2014/01/14  12:34
00000002              |       2014/01/14  17:34

I want to do a select statement where I will get the min and the max datetime of employee per day something like this:

Employee_Number       |       DateTime             MIN                  MAX
00000001              |       2014/01/14      2014/01/14  09:20    2014/01/14 22:49
00000001              |       2014/01/15      2014/01/15  09:35    2014/01/15 17:35
00000002              |       2014/01/14      2014/01/14  09:20    2014/01/14  17:34

I already searched google to find answer to my dilemma but the very near sql statement that I can have is this:

declare @tmp table (
tranDate int,
tranTime datetime

                   )

 insert into @tmp
 select Convert(int, convert(nvarchar(100), DateTime,112)) ,DateTime from tblExtract

 select tranDate, min(tranTime) as 'min' , max(tranTime) as 'max' from @tmp
 group by tranDate

The problem is it only shows the min and max of the day not per employee_number. How can I solve this?

Lucas Juan
  • 351
  • 5
  • 9
  • 23

4 Answers4

2

try this, assuming that the DateTime column is not stored as a string

select Employee_Number, Cast([DateTime] as Date) as 'DateTime', MIN([DateTime]) as 'MIN', MAX([DateTime]) as 'MAX' 
from Employee_Table
group by Employee_Number, Cast([DateTime] as Date)
Leo
  • 14,625
  • 2
  • 37
  • 55
  • Yup, I guess it's the simplest way to do it without having to create a temp table – Leo Mar 25 '14 at 02:47
1
Select DateAdd(d, 0, DateDiff(d, 0, DateTime)) tranDate, Employee_Number, min(DateTime), max(DateTime)
From tblExtract
Group By 
DateAdd(d, 0, DateDiff(d, 0, DateTime)), Employee_Number
Ken
  • 336
  • 1
  • 6
1

In MSSQL:

 select 
    emloyee_id,
    convert(date,datetime) as Date_time
    min(datetime) as Min_date,
    max(datetime) as Max_date  
 from tblEmployee
 group by emloyee_id,convert(date,datetime)

group by based on employee_id and datetime (extracting only date part) will give us one row per combination of employee_id and date ,then we can select min and max of each group

A_V
  • 11
  • 2
0

First of all, you must add Employee_Number to the tmp table.

Next, In the last statement, you must write

group by tranDate, Employee_Number

The reason is that you will get the minimum corresponding to each tranDate and Employee_Number pair, as required.

sidrakesh
  • 234
  • 2
  • 18