【问题标题】:sql function for the most recent value in a grouping用于分组中最新值的 sql 函数
【发布时间】: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


    【解决方案1】:

    您可以使用窗口函数来做到这一点。一种方法是使用条件聚合:

    select cast(left(convert(varchar(255), StuffPriceTime, 120), 16) + ':00' as datetime),
           max(case when seqnum = 1 then StuffPrice end) as FirstPrice,
           max(case when seqnum = cnt then StuffPrice end) as LastPrice
    from (select s.*,
                 row_number() over (partition by left(convert(varchar(255), StuffPriceTime, 120), 16)
                                    order by StuffPriceTime) as seqnum,
                 count(*) over (partition by left(convert(varchar(255), StuffPriceTime, 120), 16)) as cnt
          from stuff s
         ) s
    group by cast(left(convert(varchar(255), StuffPriceTime, 120), 16) + ':00' as datetime);
    

    这也将日期/时间逻辑更改为使用字符串,因为它更短。

    注意:您也可以使用 first_value()last_value() 执行此操作。但是,在 SQL Server 中,这些只能作为窗口函数使用,因此您仍然需要子查询。

    【讨论】:

    • 非常感谢,“maxprice”是从哪里来的(第 3 行)?
    • @radpin 。 . .我正在做的另一个项目。那应该是cnt
    • 这非常适合我的需要,谢谢。我在做生意!
    猜你喜欢
    • 2010-12-04
    • 2021-03-22
    • 1970-01-01
    • 2015-02-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-21
    相关资源
    最近更新 更多