这是我的表格看起来像:
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
我想做一个select语句,我会得到每天员工的最小和最大日期时间:
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
我已经搜索谷歌找到我的困境的答案,但我可以拥有的非常接近的sql声明是这样的:
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
问题是它只显示每天的最小值和最大值而不是每个employee_number。我该如何解决这个问题?
答案 0 :(得分:2)
尝试此操作,假设DateTime
列未存储为字符串
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)
答案 1 :(得分: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
答案 2 :(得分:1)
在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)
基于employee_id和datetime(仅提取日期部分)的分组将为employee_id和date的每个组合提供一行,然后我们可以选择每个组的最小值和最大值
答案 3 :(得分:0)
首先,您必须将Employee_Number添加到tmp表。
接下来,在最后一个声明中,你必须写
group by tranDate, Employee_Number
原因是您将根据需要获得与每个tranDate和Employee_Number对相对应的最小值。