如何比较最后一条记录和最后一条记录 - 1?

时间:2015-09-01 03:31:37

标签: sql sql-server

假设我有一个来自联接的表格选择如下:

No.Transaction   Item Name   PRICE
TC0001           Book        15
TC0001           Pencil      2
TC0001           Eraser      1
TC0002           Book        12
TC0002           Eraser      1.5
TC0003           Pencil      1.8
TC0003           Book        20

我想比较相同商品名称的最后价格和之前的价格。例如Book is 20 and 12Pencil is 1.8 and 2

我该怎么做?

3 个答案:

答案 0 :(得分:6)

我认为您需要这样的查询:

;WITH t AS (
    SELECT *
        , ROW_NUMBER() OVER (PARTITION BY [Item Name] 
                             ORDER BY [No.Transaction] DESC) As seq
    FROM yourTable)
SELECT t1.[Item Name]
    , t1.PRICE As lastPrice
    , t2.PRICE As preLastPrice
    , t1.PRICE - ISNULL(t2.PRICE, 0) As changePrice
FROM t t1
    LEFT JOIN
     t t2 ON t1.[Item Name] = t2.[Item Name] AND t1.seq = t2.seq - 1
WHERE (t1.seq = 1);

[SQL Fiddle Demo]

答案 1 :(得分:3)

您必须找到用于订购结果的列,然后使用DENSE_RANK()并获得最后一行

SELECT *
(
    SELECT transactionId
        ,itm_name
        ,price
        ,DENSE_RANK() OVER (PARTITION BY itm_name ORDER BY created_date DESC) AS [rank]
    FROM tbl
) res
WHERE res.[rank] IN (1,2)
ORDER BY res.[rank] 

答案 2 :(得分:-2)

查询操作。添加group by,limit(2),命令DESC。你应该得到你需要的东西。