简体   繁体   English

SQL Select基于两行之间的差异

[英]SQL Select based on difference between two rows

I am trying to work out how to easily select records based on the difference between two rows. 我试图找出如何轻松地基于两行之间的差异选择记录。

I have a table like this. 我有一张这样的桌子。

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      |  

I need to do different reports based on the % difference between the stores at different times. 我需要根据不同时间之间商店之间的百分比差异来做不同的报告。

An example. 一个例子。

Select all stores ranked 1 where >= to 3 from the store ranked 2 从排名2的商店中选择所有排名1的商店,其中>=到3

So in this case it would only select 13:50 Swindon because the difference in % is just over 3%. 因此,在这种情况下,它只会选择13:50 Swindon,因为%的差异刚刚超过3%。

There are other variations but I am sure once I have an answer to this I can work out the rest myself. 还有其他变体,但是我敢肯定,一旦得到答案,我自己就能解决剩下的一切。

I know normal select statements but I am thinking I have to do a join but just not sure how. 我知道普通的select语句,但我认为我必须进行联接,但不确定如何执行。

Based on the information given above I suppose something like this: 根据上面给出的信息,我想是这样的:

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

The column names are a bit off, but I imagine the ranking is based on time. 列名有些偏离,但我想排名是基于时间的。

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 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM