【发布时间】:2015-02-27 19:21:11
【问题描述】:
我有一个看起来有点像这样的表:
create table Stuff
(StuffID int identity not null,
StuffPrice decimal (8,2) not null,
StuffPriceTime datetime not null)
我按分钟分组,所以我可以看到价格。我的查询如下所示:
Select functionNeeded(StuffPrice),
CAST(datepart(month,StuffPriceTime ) as varchar(20))
+ '/' +
CAST(datepart(day,StuffPriceTime) as varchar(20))
+ '/' +
CAST(datepart(year,StuffPriceTime ) as varchar(20))
+ ' ' +
CAST(datepart(hour,StuffPriceTime ) as varchar(20))
+ ':' +
CAST(datepart(minute,StuffPriceTime ) as varchar(20))
as datetime) as StuffPriceTime
如果我使用 AVG(),它将平均在一分钟内发生的 StuffPrice 金额。我实际上正在寻找的是那一分钟内最新的 StuffPrice。我认为 MAX() 会选择当前最高的 StuffPrice,不一定是最近的。
换一种说法,如果我有这样的四行:
145, 10.02, 2014-12-31 09:21:15.000
147, 10.89, 2014-12-31 09:21:24.000
163, 10.71, 2014-12-31 09:21:38.000
181, 10.54, 2014-12-31 09:21:59.000
我可以将它们全部分组到 09:21:00 的时间段中,但我想要 10.54 值,因为它代表该时间段/分组的最新值(分组的最高日期时间值)。
【问题讨论】:
标签: database tsql stored-procedures sql-server-2012