使用DatePart函数进行时间查询

时间:2017-06-26 12:36:51

标签: sql ms-access

根据我所读到的内容,我创建了以下查询,按时间对所有内容进行分组,先按秒进行分组,然后将它们转换为hh:mm:ss格式:

SELECT Exits.Categorization, Format(Sum(DatePart("h",[Time_after_Search])*3600+DatePart("n",[Time_after_Search])*60)) AS TotalSeconds, Round([TotalSeconds]/3600,0) & ':' &  Right("00" &  Round(((TotalSeconds/3600) + Round(TotalSeconds/3600,0))*60,0),2) AS TotalTime
FROM Exits
GROUP BY Exits.Categorization;

非常奇怪的是,对于某些分组,秒和hh之间的转换:mm:ss完全正确。然而对于其他群体,我注意到当你将秒转换为hh:mm:ss格式时,它大部分都会关闭1200秒。为什么世界会发生这种情况?这是我查询的结果,所以你可以看到。例如,如果您看到第一个类别,则CAS编号正常工作。然而,化学品应该产生204360而不是203160(我的意思是等效的小时数),等等。

Categorization   TotalSeconds   TotalTime
                         1080   0:18
Brand Name              74880   21:08
CAS Number              37200   10:20
Catalog Numbers        522960   145:16
Chemical               203160   56:46
Generic Term            34860   10:81
Mistake???                  0   0:00
Product Characteristic 254640   71:04
Product Type           382560   106:36
Supplier Name           55560   15:26
Supplier Part Number   992160   276:96

1 个答案:

答案 0 :(得分:0)

使用这样的函数:

Public Function FormatHourMinute( _
  ByVal datTime As Date, _
  Optional ByVal strSeparator As String = ":") _
  As String

' Returns count of days, hours and minutes of datTime
' converted to hours and minutes as a formatted string
' with an optional choice of time separator.
'
' Example:
'   datTime: #10:03# + #20:01#
'   returns: 30:04
'
' 2005-02-05. Cactus Data ApS, CPH.

  Dim strHour       As String
  Dim strMinute     As String
  Dim strHourMinute As String

  strHour = CStr(Fix(datTime) * 24 + Hour(datTime))
  ' Add leading zero to minute count when needed.
  strMinute = Right("0" & CStr(Minute(datTime)), 2)
  strHourMinute = strHour & strSeparator & strMinute

  FormatHourMinute = strHourMinute

End Function

然后,在您的查询中:

SELECT 
    Exits.Categorization, 
    Sum(DateDiff("s", #00:00#, [Time_after_Search])) AS TotalSeconds,
    FormatHourMinute(Sum([Time_after_Search])) AS TotalTime
FROM 
    Exits
GROUP BY 
    Exits.Categorization;

或者也许:

SELECT 
    Exits.Categorization, 
    DateDiff("s", #00:00#, Sum([Time_after_Search])) AS TotalSeconds,
    FormatHourMinute(Sum([Time_after_Search])) AS TotalTime
FROM 
    Exits
GROUP BY 
    Exits.Categorization;