2013-03-15 95 views
3

我有,我儲存乏燃料的發票和公里的汽車曾經加油表,結構如下:SQL查詢 - 過濾從特定的行值到結果

enter image description here

我的目標是爲了得到如下結果,我可以計算髮票的公里數。

enter image description here

任何關於我如何能結構中的查詢,以獲得所需的結果建議嗎?

+0

這些是關於一輛車的所有記錄嗎? – Kaf 2013-03-15 11:21:09

+0

您使用哪種RDBMS? – 2013-03-15 11:21:18

+0

是@卡夫,只與一輛車相關。 – 2013-03-15 11:25:59

回答

2
SELECT Date, 
     (SELECT MAX(Kms) FROM invoices i2 WHERE i2.Kms < i1.Kms) AS StartKm, 
     Kms AS FinishKm 
FROM invoices i1 
ORDER BY Kms 

參見:SQL Fiddle Demo

2
;WITH Invoices AS 
(
    SELECT 456 AS Invoice, '2013-03-01' AS [Date], 145000 AS Kms 
    UNION ALL 
    SELECT 658 AS Invoice, '2013-03-04' AS [Date], 145618 AS Kms 
    UNION ALL 
    SELECT 756 AS Invoice, '2013-03-06' AS [Date], 146234 AS Kms 
), OrderedInvoices AS 
(
    SELECT Invoice, [Date], Kms, ROW_NUMBER() OVER(ORDER BY [Date]) AS RowNum 
    FROM Invoices 
) 

SELECT i1.[Date], i2.Kms AS StartKms, i1.Kms AS FinishKms 
FROM OrderedInvoices AS i1 
LEFT JOIN OrderedInvoices AS i2 
    ON i1.RowNum = i2.RowNum + 1 
1

使用CTERow_number()

;with cte as (
    select Invoice, [Date], kms, row_number() over(order by [date]) rn 
    from yourTable 
) 

select c1.[Date], c2.kms StartKms, c1.kms EndKms 
from cte c1 left join cte c2 on c1.rn = c2.rn +1 
order by c1.[Date]