根据下表,(两种服务器风格)的最佳方法是什么:
在一分钟/小时/天内对所有行进行分组并获得最大列“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),而不是总和。
答案 0 :(得分:1)
对于SQL Server
-- Last 30 days grouped by day
select dateadd(day, datediff(day, 0, 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, datediff(day, 0, D.[TimeStamp]), 0)
-- Last day grouped by the hour
select dateadd(hour, datediff(hour, 0, D.[TimeStamp]), 0) as [Hour],
max(D.CounterC) as MaxC
from DE0000000D102D1D as D
where D.[TimeStamp] between dateadd(d, -1, getdate()) and getdate()
group by dateadd(hour, datediff(hour, 0, D.[TimeStamp]), 0)
答案 1 :(得分: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, -30, 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`, max(D.CounterC) as MaxC
from `DE0000000D102D1D` as D
where D.`TimeStamp` between timestampadd(day, -1, now()) and now()
group by date_format( timestamp,'%Y:%m:%d %H' )
order by `Hour` ASC;