2014-02-17 73 views
0

我有如下表:SQL查詢下一個最低值

_id price gallons odometer 
1 3.19 15 10000 
2 3.25 13.2 10200 
3 3.24 14.8 10400 
4 3.31 15.3 10600 
5 3.31 12.8 11000 
6 3.29 12.9 10800 
7 3.32 14.3 10900 
8 3.28 15.1 11200 
9 3.27 11.7 11400 
10 3.21 14.7 11600 

我需要通過使用當前里程錶讀數來計算燃油里程,與以前相比,並加侖的量。我的問題是,如果里程錶讀數不會爲了進入(或者,如果用戶可以追溯到改變一個的值,我該如何計算新MPG?)

例子:

_id price gallons odometer 
1 3.19 10 10000 <-- First entry has no MPG rating since there is no previous data 
2 3.25 10 10200 <-- 20 MPG based off the difference of row 2 & 1 and 10 gallons 
3 3.24 10 10400 <-- 20 MPG based off the difference of row 3 & 2 and 10 gallons 
4 3.31 10 10600 <-- 20 MPG based off the difference of row 4 & 3 and 10 gallons 
5 3.31 10 11000 <-- This row will initially show 40MPG difference of row 5 & 4 (since row 6 isnt in yet) 
6 3.29 10 10800 <-- once this is entered, it goes to 20MPG difference of 6 & 4 (4 is next lowest odometer reading after 6) and then 10 becomes 20MPG difference from 5 & 6 

我認爲你可以看到我要去哪裏。從里程錶欄中,當我計算MPG時,我需要始終抓住下次最低的里程錶讀數,這應該來自最先前的條目。在某些情況下,如果用戶返回並編輯它,或者可能跳過並在稍後添加它,則需要對此進行調整。

這是所有進入Android應用程序,但我主要是如何編寫SQL的好奇。我可能需要做一些If語句並遍歷所有值或其他東西?尋找任何人的輸入。

如果您需要進一步說明,請讓我知道。

謝謝

+0

只需確認,ID列不會總是按照里程錶升序排列?例如,第9行的里程錶讀數可能低於第8行,具體取決於何時輸入數據? –

+0

這是正確的 – Rob

+0

例如,某人可能會忘記放入一個條目,然後在意識到他們忘記了之後再登錄。這可能是錯誤的 – Rob

回答

0

這應該給你你需要的成分。我不明白你的MPG計算,但是它有當前和以前的里程錶和加侖值到同一行,這應該允許你做你需要做的事情。

select x.*, 
     y.odometer as prev_odom, 
     y.gallons as prev_gallons, 
     (x.odometer - y.odometer)/x.gallons as mpg 
    from tbl x, tbl y 
where y.odometer = 
     (select max(z.odometer) from tbl z where z.odometer < x.odometer) 
union 
select x.*, null, null, null 
from tbl x 
where id = 1 
order by 1 

SQL小提琴演示:http://sqlfiddle.com/#!7/394d7/36/0

編輯 - 不得不改變以前的里程錶通過case語句上顯示ID爲2 0。 再次編輯 - Incoporated MPG計算

0

因爲它是一個應用程序,你不必一步到位做所有事情。我不知道android編程,所以我會告訴你具有通用代碼的邏輯。

currentOdometerReading = 11000; 

運行此查詢,通過上述變量作爲一個放慢參數

select gallons, 
(select max(odometer) 
from yourTable 
where odometer < @paramterFromYourApp) prevOdometerReading 
where odometer = @paramterFromYourApp 

回您的應用程序

milesPerGallon = (currentOdometerReading - thePrevOdometerReadingValue from your query) 
/theGallonsValueFromYourQuery; 

只要記住,如果一個記錄還沒有進入呢,這不會給出正確的答案。但是再一次,其他任何事情都不會發生。那將是一個你不尋找最新數據的過程。