如何编写sql查询来计算时间不同

时间:2011-10-08 17:55:25

标签: sql sql-server

I have table structure like this

EnrollNo,Date,Time

1, 8-10-2011 12:00:32 , 13:12 
1, 8-10-2011 12:00:32 , 23:14 
2, 8-10-2011 12:00:32 , 11:12 
2, 8-10-2011 12:00:32 , 20:14 
3, 8-10-2011 12:00:32 , 12:12 
3, 8-10-2011 12:00:32 , 23:14 
4, 8-10-2011 12:00:32 , 17:12 
4, 8-10-2011 12:00:32 , 23:14


Data Type for EnrollNo is int, Date is Datetime, Time is text

I want out put like below

EnrollNo, Date, TimeDiff, Timein, Timeout

1, 8-10-2011 12:00:32, 10:02 , 13:12, 23:14
2, 8-10-2011 12:00:32, 09:02 , 11:12, 20:14 
3, 8-10-2011 12:00:32, 11:02 , 12:12, 23:14 
4, 8-10-2011 12:00:32, 06:02 , 17:12, 23:14

3 个答案:

答案 0 :(得分:1)

您可以按(EnrollNo, Date)分组,并使用min()max()查找签到和结帐时间。使用datediff,您可以找到时差。

select  EnrollNo
,       [Date]
,       right('0' + cast(datediff(hour, cast(min(Time) as datetime), 
            cast(max(Time) as datetime)) as varchar(2)),2) + ':' +
        right('0' + cast(datediff(minute, cast(min(Time) as datetime), 
            cast(max(Time) as datetime)) % 60 as varchar(2)),2)
,       min(Time)
,       max(Time)
from    @t
group by
        EnrollNo
,       [Date]

SQL格式化很难;如果以秒为单位传递时间差,则查询会更容易,并让客户端应用程序进行格式化。

Full example at SE Data.

答案 1 :(得分:0)

Select enrollNo, DateAdd(day, datediff(day, 0, date), 0) Date,
    Convert(varChar(5), Cast(Max(date) - Min(date) as DateTime), 4) timediff, 
    Convert(varChar(5), Min(date), 4) Timein, 
    Convert(varChar(5), Max(date), 4) Timeout
From @t
Group By DateAdd(day, datediff(day, 0, date), 0)

答案 2 :(得分:0)

你试过在sql http://msdn.microsoft.com/en-us/library/ms189794.aspx中使用datediff函数吗? 找出入住/退房的差异?