1

我有一个数据库表,其中有一列OccurDatedatatype DateTime

数据是这样的...

06-03-2013 06:47:49
06-03-2013 16:47:49

我必须找到 InTime、OutTime、WorkDuration。

我正在使用这样的查询

Min(convert(varchar(10),OccurDateTime,108)) AS InTime,
Max(convert(varchar(10),OccurDateTime,108)) AS OutTime,

但我在计算时遇到workDuration了问题,因为

workDuration = 16:30:00 - InTime    //16:30:00 means 4:30 pm

而银泰现在是varchar(10)这样,它不能减去Datetime......

我正在使用的查询..

SELECT UserID AS EmpCode,FirstName,LastName,Department,convert(varchar(10),OccurDateTime,103) AS Date,Min(convert(varchar(10),OccurDateTime,108)) AS InTime,
Max(convert(DateTime,OccurDateTime,108)) AS OutTime,
convert(varchar(10),(Max(convert(DateTime,OccurDateTime,108))- Min(convert(DateTime,OccurDateTime,108))),108) as Work,

FROM TTransactionLog1
WHERE convert(varchar(10),OccurDateTime,103) = '14/03/2013'
GROUP BY UserID, FirstName, convert(varchar(10),OccurDateTime,103),LastName,Department

所以你们有什么想法......

4

3 回答 3

2

您应该寻找的Min/Max Dates 不是Min/Max of varchar. 因此,在将它们转换为 varchar 之前检查 Dates 并将它们转换为所需格式的最终​​结果。

此外,您必须使用Datediff函数来获取difference of Max and Min dates,当您将字符串作为日期传递时,请使用ISO format( 'yyyymmdd'),即NOT culture specific. 否则,您的查询可能无法在具有不同文化设置的服务器中工作。

我认为以下查询应该有效:

SELECT UserID AS EmpCode, FirstName, LastName, Department,
       --Convert(varchar(10), OccurDateTime, 103) AS  Date,
       Convert(varchar(10), Min(OccurDateTime), 108) AS InTime,
       Convert(varchar(10), Max(OccurDateTime), 108) AS OutTime,
       Convert(varchar(10), 
           Datediff(day,Min(OccurDateTime), Max(OccurDateTime)),108) as Work
FROM TTransactionLog1
WHERE OccurDateTime  = '20130314' --Note: ISO format 
GROUP BY UserID, FirstName, --OccurDateTime, 
        LastName, Department
于 2013-03-15T12:03:18.323 回答
1
WITH A AS (SELECT CONVERT(DATETIME, '16:25:00') InTime)
SELECT
CONVERT(varchar(10),CONVERT(DATETIME, '16:30:00') - InTime,108) workDuration
FROM A  

输出:我相信双重转换会导致00:05:00
datetime计算后计算convertvarchar

于 2013-03-15T12:00:19.427 回答
0

如果要计算两个日期时间之间的间隔,请使用 datediff()。

于 2013-03-15T12:00:04.077 回答