建表脚本
CREATE TABLE [dbo].[DeviceDetails](
[DeviceDetailsId] [int] IDENTITY(1,1) NOT NULL,
[InDate] [datetime] NOT NULL,
[OutDate] [datetime] NOT NULL,
[DeviceId] [int] NOT NULL,
[Uuid] [nvarchar](50) NOT NULL,
CONSTRAINT [PK_DeviceDetails] PRIMARY KEY CLUSTERED
(
[DeviceDetailsId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
INSERT INTO [dbo].[DeviceDetails]
([InDate]
,[OutDate]
,[DeviceId]
,[Uuid])
VALUES
('2014/8/6 9:44:56','2014/8/6 15:37:40',3,'SC67A3623F2B4D1EB6F7C35BEB9E791A')
我要统计今天每5分种的在线人数。
从0点开始到当前时间
我的语句如下
SELECT count(*) as c
FROM [dbo].[DeviceDetails]
where '2014/8/6 0:05:00' between indate and outdate
union
SELECT count(*) as c
FROM [dbo].[DeviceDetails]
where '2014/8/6 0:10:00' between indate and outdate
union
SELECT count(*) as c
FROM [dbo].[DeviceDetails]
where '2014/8/6 0:15:00' between indate and outdate
我去,这得多少个union啊,这语句该多长啊。
ps:这个表有百万条纪录。求助优化。
------解决方案--------------------
http://bbs.csdn.net/topics/390839951
我解答过的这个帖子跟你情况一模一样,你看一下就可以解决你的问题了
------解决方案--------------------
select dateadd(n,a.number*5,'20140806') as times,count([DeviceDetailsId]) as [count]
from master..spt_values a
left join [DeviceDetails] b on dateadd(n,a.number*5,'20140806') between b.indate and b.outdate
where a.type='p' and a.number between 1 and 288
group by dateadd(n,a.number*5,'20140806')