0

我有一个查询,它返回对按日期采样的不同对象的请求数,每天可以有多个采样器。开头的 With 部分用于每天只获取最新的样本。

With RankedSamples As
    (
    Select  Id, runend
        , ROW_NUMBER() OVER( PARTITION BY convert(varchar , runEnd, 1) ORDER BY runEnd DESC ) ItemRank
    From t_SamplesRuns
    where runend > '05/13/12' and runend < '05/18/12'
    )

select sum(TotalRequests) Hits, 
       convert(nvarchar(10), day(smp.date)) + '-' + 
       convert(nvarchar(10), month(smp.date)) + '-' + 
       convert(nvarchar(10), year(smp.date)) date
from t_samples smp
where  smp.runid in (                 
    select id                 
    from RankedSamples                 
    where ItemRank = 1  
    )    

group by convert(nvarchar(10), day(smp.date)) + '-' + 
         convert(nvarchar(10), month(smp.date)) + '-' + 
         convert(nvarchar(10), year(smp.date))

这返回的是例如:

Hits     date
111111   13-5-2012
222222   14-5-2012
333333   15-5-2012
444444   16-5-2012
555555   17-5-2012

我需要它返回的是这些字段+前一天的点击次数及其减法(第一行无关):

Hits     date       Prev     Res
111111   13-5-2012  0        111111
222223   14-5-2012  111111   111112
333335   15-5-2012  222223   111113 
444447   16-5-2012  333335   111114
555559   17-5-2012  444447   111115

有任何想法吗?谢谢!

4

1 回答 1

2

假设你没有使用 SQL Server 2012,你想要做的是实现一个滞后函数。不幸的是,最简单的方法是使用自联接。所以,我要重写你的查询来做到这一点:

With RankedSamples As (
      Select Id, runend,
             ROW_NUMBER() OVER( PARTITION BY convert(varchar , runEnd, 1) ORDER BY runEnd DESC) as ItemRank
      From t_SamplesRuns
      where runend > '05/13/12' and runend < '05/18/12'
    )
     Results as (
      select sum(TotalRequests) Hits,
             convert(nvarchar(10), day(smp.date)) + '-' +  convert(nvarchar(10), month(smp.date)) + '-' +         convert(nvarchar(10), year(smp.date)) as date
      from t_samples smp where  smp.runid in (select id from RankedSamples where ItemRank = 1)
      group by convert(nvarchar(10), day(smp.date)) + '-' +  convert(nvarchar(10), month(smp.date)) + '-' +  convert(nvarchar(10), year(smp.date)
    ),
     Results2 as (
         select r.*, row_number() over (partition by null order by date) as rownum
         from Results
    )
select r.hits, r.date, rprev.hits, r.hits - rprev.hits
from Results2 r left outer join
     Results2 rprev
     on r.rownum = rprev.rownum+1

正如我所说,这在 SQL Server 2012 中更容易,因为窗口函数更类似于 Oracle 的分析函数。

于 2012-05-22T14:20:02.007 回答