【问题标题】:custom aggregate function or equivalent in sql serversql server 中的自定义聚合函数或等效函数
【发布时间】:2014-02-11 19:28:31
【问题描述】:

SQL Server 编程新手,想看看我是否可以就这个查询获得帮助。 假设我有一张表 LatencyInfo

DateTime              Latency
2014-01-21 00:00:00    12334
2014-01-21 00:00:00    56384
2014-01-20 00:00:00    1232
2014-01-20 00:00:00    4353
2014-01-19 00:00:00    434343

我的目标是在查询中找到每天第 95 个百分位的延迟时间。所以,到目前为止,我能够想出一个日期的第 95 个百分位,但我坚持在日期上聚合它。我无法使用 PERCENTILE-CONT,因为我正在使用的 sql server 版本不支持此查询。

select MIN(P.latency) 
from
  (select top 5 PERCENT S.latency as PerLatencyInfo 
    from
      (select convert(varchar(20), datetimefield, 1) as datefield
             ,latency
       from LatencyInfo
       where datetimefield >= '2014-01-21 00:00:00'
      ) as S
    order by S.latency DESC
  ) as P

非常感谢任何帮助。我无法在此处尝试 CLR 聚合,因为我无法在服务器上安装 .NET 框架。

如果我不能使用自定义聚合函数,即使我可以在任何其他等效逻辑上获得帮助,那也很棒。

使用 Sql Server 11.0.9

【问题讨论】:

标签: sql sql-server sql-server-2012 aggregate-functions


【解决方案1】:

您应该看看 NTILE 窗口函数。

在下面的示例中,我使用了 NTILE(20),这会将返回的行拆分为 5% 的块,并为每个块分配一个从 1 到 20 的数字。

SELECT   [DateTime], Latency
FROM    ( SELECT    [DateTime], 
        Latency, 
        NTILE(20) OVER ( PARTITION BY cast([DateTime] as date) ORDER BY Latency ASC) Top5
          FROM      latencyInfo
        ) x
WHERE   Top5 = 1

在 DateTime 上对行进行了分区,以便它在每个日期执行 NTILE 函数并按延迟升序排序(最小的在顶部的 NTILE 中)。 p>

然后我要做的就是选择最高百分位数的所有内容。 (Top5 = 1)

【讨论】:

    【解决方案2】:

    在 SQL Server 2005 或更高版本中,您可以使用窗口函数并做同样的事情:

    select cast(datetime as date) as thedate, latency
    from (select pli.*,
                 row_number() over (partition by cast(datetime as date) order by latency) as seqnum,
                 count(*) over (partition by cast(datetime as date)) as daycnt
          from PerLatencyInfo
         ) pli
    where seqnum = 0.95 * daycnt;
    

    seqnum 列仅列举每天从最低延迟到最高延迟的值。 daycnt 的值是当天的总数。第 95 个百分位在 where 子句中计算。

    一些笔记。

    • SQL Server 2005 不支持cast( as date),但还有其他机制,例如您的convert()
    • 这不会在值之间进行插值。

    【讨论】:

    • 您的意思是 SQL Server 2008 或更高版本?因为在你的笔记中你说CAST( AS DATE) 不适用于 2005 年?
    • @NickyvV 解析/窗口函数在 2005+ 可用,DATE 在 2008+。
    • @NickyvV 。 . .我只是认为cast(date as date) 是最好的语法,但还有其他方法。正如另一条评论中提到的,我使用的窗口函数可用于 SQL Server 2005 及更高版本。
    猜你喜欢
    • 1970-01-01
    • 2011-05-21
    • 2013-08-14
    • 1970-01-01
    • 2018-10-15
    • 2020-08-05
    • 2019-11-05
    • 1970-01-01
    • 2016-10-12
    相关资源
    最近更新 更多