SQL查询 - 将特定行的过滤值转换为结果

时间:2013-03-15 11:18:36

标签: sql sql-server

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

enter image description here

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

enter image description here

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

3 个答案:

答案 0 :(得分: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 :(得分: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 :(得分: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]