繁体   English   中英

分组和汇总列

[英]Grouping and summarize columns

根据下表,(在两种服务器风格中)最佳方法是什么:

在分钟/小时/天之内将所有行分组,并获得最大的列“ CounterC”?

示例:在“现在”和“现在”之间-1天之间,每小时可获得Max(CounterC)。 示例2:在“现在”和“现在”之间-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, 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)

对于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;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM