2013-03-16 44 views
0

我需要生成一些SQL,它会显示一些交易中的趋势(上或下)。分析TSQL

如果我从3/15提取数据我有一个上升的趋势得分12比历史数据,考虑这个表有PlayerId和分数

PlayerId, Score, Date 
1,10,3/13 
1,11,3/14 
1,12,3/15 

我确实在大约10年前,甲骨文8i中类似的东西使用一些像排名分析功能,但它是10年前....

结果将类似于

PlayerId, Score, Date, Trend 
1,12,3/15,UP 

我怎样才能做到与SQL Azure类似的东西?

+0

你可以充分利用所有的平均值,并比较最新的,如果最新的是大于平均值,则走势是吗?如果不是,那么你如何界定什么是“趋势”? – Matthew 2013-03-16 18:58:55

回答

3

这个SQL:

with data as (
    select * from (values 
    (1,11,cast('2013/03/12' as smalldatetime)), 
    (1,15,cast('2013/03/13' as smalldatetime)), 
    (1,11,cast('2013/03/14' as smalldatetime)), 
    (1,12,cast('2013/03/15' as smalldatetime)) 
) data(PlayerId,Score,[Date]) 
) 
select 
    this.*, 
    Prev = isnull(prev.Score,0), 
    tick = case when this.Score > isnull(prev.Score,0) then 'Up' else 'Down' end 
from data this 
left join data prev 
    on prev.PlayerId = this.PlayerId 
    and prev.[Date]  = this.[Date] - 1 

返回此输出:

PlayerId Score  Date     Prev  tick 
----------- ----------- ----------------------- ----------- ---- 
1   11   2013-03-12 00:00:00  0   Up 
1   15   2013-03-13 00:00:00  11   Up 
1   11   2013-03-14 00:00:00  15   Down 
1   12   2013-03-15 00:00:00  11   Up 
+0

谢谢。这使我走上了正确的道路。 – jason 2013-03-16 20:16:52