SQL Server 2008 - 将结果分组为5分钟

时间:2016-12-08 07:47:26

标签: sql-server-2008 tsql

我目前有一个SQL脚本,它返回从导入文件处理到数据库中的数据项的结果,但是我们正在考虑计算进入数据库的项目数,分为5分钟,在规定的一天。

我现有的脚本如下:

declare @date datetime
set @date = '2016-12-07 00:00:00.000

Select filename, IE.dateprocessingstarted
  from tdii_inboundprocessed IE 
  inner join consignmentpf cpf
      on ie.inboundfileprocessedid = cpf.inboundprocessedid
where 1=1 and (ie.dateprocessingstarted between `@date` and `dateadd(dd,1,@date)`

返回以下内容:

FilenameDate ProcessingStarted

GOOD813546 2016-12-07 00:02:00
GOOD813546 2016-12-07 00:02:00
GOOD813546 2016-12-07 00:02:00
GOOD813546 2016-12-07 00:02:00
GOOD813546 2016-12-07 00:02:00
GOOD813546 2016-12-07 00:02:00
GOOD813554 2016-12-07 00:08:00
GOOD813554 2016-12-07 00:08:00
GOOD813554 2016-12-07 00:08:00
GOOD813554 2016-12-07 00:08:00

我希望看到的是:
datetime numberoffiles
2016-12-07 00:05:00 6
2016-12-07 00:10:00 4

tdii_inboundprocessed表包含进入系统的文件的详细信息,包括我们对dateprocessingstarted感兴趣的时间)consignmentpf表包含特定文件中项目的详细信息,这是我们有兴趣获取计数的数字

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

SELECT  t.date ,
        COUNT(*)
FROM    ( SELECT    DATEADD(MINUTE,
                            ( ( DATEDIFF(MINUTE, @date,
                                         IE.dateprocessingstarted) / 5 ) * 5 )
                            + 5, @date) [date]
          FROM      @tdii_inboundprocessed IE
                    INNER JOIN consignmentpf cpf ON IE.inboundfileprocessedid = cpf.inboundprocessedid
          WHERE     1 = 1
                    AND ( IE.dateprocessingstarted BETWEEN @date
                                                   AND     DATEADD(dd, 1,
                                                              @date) )
        ) AS t
GROUP BY t.date;