1

我有这个查询来计算我数据库中所有油箱的当前加仑值。

SELECT DISTINCT y.TankNumber as TankNumber
    , y.Gallons as Gallons
    , y.timeUpdated
    , y.FuelType as FuelType
FROM (
    SELECT TankNumber, max(timeUpdated) as maxdate
    FROM someTable
    GROUP BY TankNumber) as x
JOIN someTable y
ON x.TankNumber = y.TankNumber
AND x.maxdate = y.timeUpdated
ORDER BY y.TankNumber

根据燃料使用情况,数据会随时自动转储到我的数据库中。上面的查询只会给我每个油箱中的当前加仑值:

TankNumber  |  Gallons  |  timeUpdated        |  FuelType
     1      |  14       |  2012-10-22 04:16   |  89
     2      |  8        |  2012-10-22 04:14   |  93

等等。
我的问题是,我正在尝试向我的页面添加另一个输出值,这将使我知道自上次更新以来使用了多少燃料。所以它看起来像这样:

TankNumber  |  Gallons  |  timeUpdated        |  FuelType  |  GallonsUsed
     1      |  14       |  2012-10-22 04:16   |  89        |  5
     2      |  8        |  2012-10-22 04:14   |  93        |  -11

不幸的是,对于这类问题,我的 SQL 经验并不那么可靠,我花了大约两天时间试图找出或用谷歌搜索接近的东西。因此,任何帮助将不胜感激。

4

1 回答 1

3

假设您使用的是 MS SQL 2005 或更高版本,您可以使用 ROW_NUMBER 函数:

WITH cteOrderedUpdates As
(
   SELECT
      TankNumber,
      Gallons,
      TimeUpdated,
      FuelType,
      ROW_NUMBER() OVER 
      (
         PARTITION BY 
            TankNumber 
         ORDER BY 
            TimeUpdated DESC
      ) As RowNumber
   FROM
      someTable
)
SELECT
   x.TankNumber,
   x.Gallons,
   x.TimeUpdated,
   x.FuelType,
   x.Gallons - IsNull(y.Gallons, 0) As GallonsUsed
FROM
   cteOrderedUpdates As x
   LEFT JOIN cteOrderedUpdates As y
   ON x.TankNumber = y.TankNumber
   And x.RowNumber = y.RowNumber - 1
WHERE
   x.RowNumber = 1
ORDER BY
   x.TankNumber
;
于 2012-10-22T16:57:56.463 回答