2014-11-03 53 views
6

表选择:通过增加订单SQL

id | year |  score 
-----+------+----------- 
    12 | 2011 |  0.929 
    12 | 2014 |  0.933 
    12 | 2010 |  0.937 
    12 | 2013 |  0.938 
    12 | 2009 |  0.97 
    13 | 2010 |  0.851 
    13 | 2014 |  0.881 
    13 | 2011 |  0.885 
    13 | 2013 |  0.895 
    13 | 2009 |  0.955 
    16 | 2009 |  0.867 
    16 | 2011 |  0.881 
    16 | 2012 |  0.886 
    16 | 2013 |  0.897 
    16 | 2014 |  0.953 

所需的输出:

id | year |  score 
-----+------+----------- 
    16 | 2009 |  0.867 
    16 | 2011 |  0.881 
    16 | 2012 |  0.886 
    16 | 2013 |  0.897 
    16 | 2014 |  0.953 

我有在尝试了在对于今年增产得分困难。 任何帮助将不胜感激。

+0

为目标,以从'id'列的最高值返回所有记录? – 2014-11-03 22:36:33

+1

您使用的是什么版本的SQL? – 2014-11-03 22:36:55

+1

你想只返回每年的最高分数吗? – Sablefoste 2014-11-03 22:38:29

回答

7

所以你想选择id = 16,因为它是唯一一个稳步增加值。

许多版本的SQL支持lag(),它可以帮助解决这个问题。您可以确定,对于一个给定的ID,如果所有的值都增加或做递减:

select id, 
     (case when min(score - prev_score) < 0 then 'nonincreasing' else 'increasoing' end) as grp 
from (select t.*, lag(score) over (partition by id order by year) as prev_score 
     from table t 
    ) t 
group by id; 

然后你可以选择全部使用“增加” ID的加入:

select t.* 
from table t join 
    (select id 
     from (select t.*, lag(score) over (partition by id order by year) as prev_score 
      from table t 
      ) t 
     group by id 
     having min(score - prev_score) > 0 
    ) inc 
    on t.id = inc.id; 
+0

所以这是为什么当相同的分数计数为'增加'?如果在下一个连续一年的重复分数不应该返回结果,那么它应该是'min(score - prev_score)> 0'? – Beth 2014-11-03 22:49:27

+0

@Beth。 。 。根据我的经验,通常当使用“增加”这个词时,它确实意味着“不减少”。同样,“积极”常常意味着“非消极”。但是,你是对的,这个问题明确地说增加了,所以我删除了'='。 – 2014-11-03 22:51:59