SQL根据两行之间的差异进行选择

时间:2014-02-25 08:35:50

标签: sql

我正在尝试找出如何根据两行之间的差异轻松选择记录。

我有一张这样的桌子。

Time  | Store   | Code | %      | Ranked |  
------------------------------------------
13:50 | Swindon | 33   | 32.578 | 1      |  
13:50 | Reading | 31   | 29.438 | 2      |  
13:50 | Bath    | 32   | 28.221 | 3      |  
14:50 | Swindon | 33   | 32.100 | 1      |  
14:50 | Reading | 32   | 30.987 | 2      |  
14:50 | Bath    | 32   | 28.335 | 3      |  

我需要根据不同时间商店之间的差异来做不同的报告。

一个例子。

从排名为2的商店中选择排名为1的所有商店>=到3

因此,在这种情况下,它只会选择13:50 Swindon,因为%的差异仅略高于3%。

还有其他的变化,但我相信一旦我得到了答案,我可以自己解决其余的问题。

我知道正常的选择陈述,但我想我必须做一个连接,但只是不确定如何。

2 个答案:

答案 0 :(得分:0)

基于上面给出的信息,我想这样的事情:

select *
from table t1
inner join table t2 on t1.Time = t2.Time and t1.Ranked = 1 and t2.Ranked = 2
where (t1.% - t2.%) > 3

列名有点偏,但我想排名是基于时间的。

答案 1 :(得分:0)

SELECT R1.store, 
       R1.timestamp 
FROM   store_tbl R1, 
       store_tbl R23 
WHERE  R1.ranked = 1 
       AND R23.ranked = 2 
       AND R1.timestamp = R23.timestamp 
       AND ( R1.percentage - R23.percentage ) > 3 
相关问题