简体   繁体   English

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

[英]How to compare last record and last record - 1?

Lets say I have a table from join select like this: 假设我有一个来自连接的表选择如下:

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

I want to compare last price and its previous price for same item name. 我想比较相同商品名称的最后价格和之前的价格。 For example Book is 20 and 12 , Pencil is 1.8 and 2 例如Book is 20 and 12Pencil is 1.8 and 2

How can I do that? 我怎样才能做到这一点?

I think you need a query like this: 我认为你需要这样的查询:

;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] [SQL小提琴演示]

you must find column for order your result then use DENSE_RANK() and get 2 last row like this 您必须找到用于订购结果的列,然后使用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] 

Query manipulation. 查询操作。 Adding group by, limit(2), order DESC . 添加group by,limit(2),命令DESC。 you should get what you needed. 你应该得到你需要的东西。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM