SQL Server:以特定时间间隔返回列

时间:2018-03-08 19:12:37

标签: sql-server sql-server-2017

我想在特定时间间隔(即01:00:00到01:05:00)之间返回行,然后计算另一列的总和。 列数据类型为TIME。我尝试过......和'命令,但它没有工作。

此外,我想每五分钟做一次相同的计算。

修改

我的查询无效

select time
from dbo.table;
where time between'01:00:00' and '01:05:00'

错误消息:关键字附近的语法错误'其中'。

示例数据:

Time      ----- Team
01:00:00  ----- Liverpool
01:06:33  ----- Liverpool
01:04:00  ----- Man. United
01:02:17  ----- Man. City
01:01:00  ----- Man. City
01:07:15  ----- Liverpool

我的预期输出,我想像

[01:00:00 - 01:05:00] ----- Man. City ----- 2
[01:00:00 - 01:05:00] ----- Liverpool ----- 1
[01:00:00 - 01:05:00] ----- Man. United ----- 1
[01:05:01 - 01:10:00] ----- Liverpool ----- 2

最后,我想循环2-3个小时。

2 个答案:

答案 0 :(得分:0)

如果您使用between来定义时间范围,则包括该范围的低点和高点。要避免范围重叠,只需使用>=<的组合来定义时间范围。

select [time]
from dbo.table
where [time] >= '01:00:00' and [time] < '01:05:00'

当使用处理multiiple范围的case表达式时,这更为重要,因此它们是互斥的。

 Select
   case 
    when [time] >= '01:00:00' and [time] < '01:05:00' then  '[01:00:00 - 01:05:00]'
    when [time] >= '01:05:00' and [time] < '01:10:00' then  '[01:05:00 - 01:10:00]'
    ...
    end
From dbo.table

答案 1 :(得分:0)

我毫不怀疑有一种计算时间间隔的方法,但我必须搜索如何做到这一点。如果您的时间间隔是静态的,那么您可以创建一个这样的表:

CREATE TABLE [dbo].[TimeIntervals](
    [Id] [INT] IDENTITY(1,1) NOT NULL,
    [TimeStart] [TIME](0) NOT NULL,
    [TimeEnd] [TIME](0) NOT NULL
) ON [PRIMARY]
GO

您的记录如下所示:

INSERT [dbo].[TimeIntervals] ([TimeStart], [TimeEnd]) VALUES (CAST(N'01:00:00' AS Time), CAST(N'01:05:00' AS Time))
GO
INSERT [dbo].[TimeIntervals] ([TimeStart], [TimeEnd]) VALUES (CAST(N'01:05:00' AS Time), CAST(N'01:10:00' AS Time))
GO
INSERT [dbo].[TimeIntervals] ([TimeStart], [TimeEnd]) VALUES (CAST(N'01:10:00' AS Time), CAST(N'01:15:00' AS Time))
GO

我还创建了一个表来保存您的示例值:

CREATE TABLE [dbo].[Times](
    [times] [TIME](7) NULL,
    [team] [VARCHAR](50) NULL
) ON [PRIMARY]
GO

INSERT [dbo].[Times] ([times], [team]) VALUES (CAST(N'01:00:00' AS Time), N'Liverpool')
GO
INSERT [dbo].[Times] ([times], [team]) VALUES (CAST(N'01:06:33' AS Time), N'Liverpool')
GO
INSERT [dbo].[Times] ([times], [team]) VALUES (CAST(N'01:04:00' AS Time), N'Man. United')
GO
INSERT [dbo].[Times] ([times], [team]) VALUES (CAST(N'01:02:17' AS Time), N'Man. City')
GO
INSERT [dbo].[Times] ([times], [team]) VALUES (CAST(N'01:01:00' AS Time), N'Man. City')
GO
INSERT [dbo].[Times] ([times], [team]) VALUES (CAST(N'01:07:15' AS Time), N'Liverpool')
GO

然后你的查询看起来像这样:

SELECT 
      ti.TimeStart
     ,ti.TimeEnd
     ,t.team
     ,COUNT(t.team)
FROM dbo.Times t
    INNER JOIN dbo.TimeIntervals ti ON t.times BETWEEN ti.TimeStart AND ti.TimeEnd
GROUP BY ti.TimeStart
    ,ti.TimeEnd
    ,t.team