3

次の構造を持つ、使用済み燃料の請求書と車が給油された km を保存するテーブルがあります。

ここに画像の説明を入力

私の目標は、次のような結果を取得することです。これにより、請求書間に費やされた km を計算できます。

ここに画像の説明を入力

クエリを構成して目的の結果を得る方法に関するアドバイスはありますか?

4

3 に答える 3

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

于 2013-03-15T11:45:08.640 に答える
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
于 2013-03-15T11:28:18.830 に答える
1

CTEと の使用Row_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] 
于 2013-03-15T11:29:37.853 に答える