问题描述
|
根据下表,(在两种服务器风格中)最佳方法是什么:
将在一分钟/小时/天之内的所有行分组,并获得最大列\'CounterC \'吗?
示例:在\'now \'和\'now \'之间-1天,每小时可获得Max(CounterC)。
示例2:在\'now \'和\'now \'之间-30天之间,每天获取Max(CounterC)。
显然,行必须分组,但是如何?
MS SQL
CREATE TABLE [dbo].[DE0000000D102D1D](
[index] [bigint] IDENTITY(1,1) NOT NULL,[TimeStamp] [datetime] NOT NULL,[CounterA] [bigint] NOT NULL,[CounterB] [bigint] NOT NULL,[CounterC] [bigint] NOT NULL,[CounterD] [bigint] NOT NULL,)
的MySQL
CREATE TABLE `de0000000d102d1d` (
`index` bigint(20) NOT NULL AUTO_INCREMENT,`TimeStamp` datetime NOT NULL,`CounterA` bigint(20) NOT NULL,`CounterB` bigint(20) NOT NULL,`CounterC` bigint(20) NOT NULL,`CounterD` bigint(20) NOT NULL,PRIMARY KEY (`index`)
)
一些示例数据:
index TimeStamp CounterA CounterB CounterC CounterD
----- ----------------------- -------- -------- --------- --------
1 2011-03-07 14:25:32.000 0 1 347406352 916
2 2011-03-07 14:26:32.000 0 1 347407169 916
3 2011-03-07 14:27:32.000 0 1 347407978 916
4 2011-03-07 14:28:31.000 0 1 347408617 916
5 2011-03-07 14:29:31.000 0 1 347409087 916
6 2011-03-07 14:30:30.000 0 1 347409557 916
7 2011-03-07 14:31:09.000 0 1 347409845 916
提前致谢!
编辑:实际上是每个间隔我想要的Max(CounterC),而不是总和。
解决方法
对于SQL Server
-- Last 30 days grouped by day
select dateadd(day,datediff(day,D.[TimeStamp]),0) as [day],max(D.CounterC) as MaxC
from DE0000000D102D1D as D
where D.[TimeStamp] between dateadd(d,-30,getdate()) and getdate()
group by dateadd(day,0)
-- Last day grouped by the hour
select dateadd(hour,datediff(hour,0) as [Hour],-1,getdate()) and getdate()
group by dateadd(hour,0)
, 对于MySQL,这是相同的查询:
-- Last 30 days grouped by day
select date_format( timestamp,\'%Y:%m:%d\' ) `day`,max(D.CounterC) as MaxC
from `DE0000000D102D1D` as D
where D.`TimeStamp` between timestampadd(day,now()) and now()
group by date_format( timestamp,\'%Y:%m:%d\' )
order by `day` ASC;
-- Last day grouped by the hour
select date_format( timestamp,\'%Y:%m:%d %H\' ) as `Hour`,\'%Y:%m:%d %H\' )
order by `Hour` ASC;