简体   繁体   中英

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

So in this case it would only select 13:50 Swindon because the difference in % is just over 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.

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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