3

我有一张桌子,用于存储乏燃料发票和汽车加油的公里数,结构如下:

在此处输入图像描述

我的目标是获得如下结果,这样我就可以计算出发票之间的公里数。

在此处输入图像描述

关于如何构建查询以获得所需结果的任何建议?

4

3 回答 3

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 回答
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 小提琴演示

于 2013-03-15T11:45:08.640 回答
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] 
于 2013-03-15T11:29:37.853 回答