将最近一行与同一 table 中的前一行进行比较
Compare the most recent row with the immediate previous in the same table
我遇到了这个问题,我需要根据相同的标准将最近的行与前一行进行比较(在本例中为 trader)。
这是我的 table:
ID Trader Price
-----------------
1 abc 5
2 xyz 5.2
3 abc 5.7
4 xyz 5
5 abc 5.2
6 abc 6
这是脚本
CREATE TABLE Sale
(
ID int not null PRIMARY KEY ,
trader varchar(10) NOT NULL,
price decimal(2,1),
)
INSERT INTO Sale (ID,trader, price)
VALUES (1, 'abc', 5), (2, 'xyz', 5.2),
(3, 'abc', 5.7), (4, 'xyz', 5),
(5, 'abc', 5.2), (6, 'abc', 6);
到目前为止,我正在使用这个还不完美的解决方案
select
a.trader,
(a.price - b.price ) New_price
from
sale a
join
sale b on a.trader = b.trader and a.id > b.ID
left outer join
sale c on a.trader = c.trader and a.id > c.ID and b.id < c.ID
where
c.ID is null
以上内容并不完美,因为我只想比较最近的和最近的……例如在这个示例中
- 交易员 abc : 我将只比较 id = 6 和 id = 5
- 交易员 xyz:id = 4 和 id = 2
感谢您的帮助!
如果您使用的是 SQL Server 2012 或更高版本,您可以使用函数 LEAD
and LAG
来连接上一个和下一个数据。不幸的是,这些功能只能在 SELECT
或 ORDER BY
子句中使用,因此您需要使用子查询来获取所需的数据:
SELECT t.trader, t.current_price - t.previous_price as difference
FROM (
SELECT
a.trader,
a.price as current_price,
LAG(a.price) OVER(PARTITION BY a.trader ORDER BY a.ID) as previous_price,
LEAD(a.price) OVER(PARTITION BY a.trader ORDER BY a.ID) as next_price
FROM sale a
) t
WHERE t.next_price IS NULL
在您的子查询中,您为上一个和下一个值创建了额外的列。然后在您的主查询中,您仅过滤下一个价格为 NULL 的这些行 - 这表明这是特定交易者的最后一行。
我遇到了这个问题,我需要根据相同的标准将最近的行与前一行进行比较(在本例中为 trader)。
这是我的 table:
ID Trader Price
-----------------
1 abc 5
2 xyz 5.2
3 abc 5.7
4 xyz 5
5 abc 5.2
6 abc 6
这是脚本
CREATE TABLE Sale
(
ID int not null PRIMARY KEY ,
trader varchar(10) NOT NULL,
price decimal(2,1),
)
INSERT INTO Sale (ID,trader, price)
VALUES (1, 'abc', 5), (2, 'xyz', 5.2),
(3, 'abc', 5.7), (4, 'xyz', 5),
(5, 'abc', 5.2), (6, 'abc', 6);
到目前为止,我正在使用这个还不完美的解决方案
select
a.trader,
(a.price - b.price ) New_price
from
sale a
join
sale b on a.trader = b.trader and a.id > b.ID
left outer join
sale c on a.trader = c.trader and a.id > c.ID and b.id < c.ID
where
c.ID is null
以上内容并不完美,因为我只想比较最近的和最近的……例如在这个示例中
- 交易员 abc : 我将只比较 id = 6 和 id = 5
- 交易员 xyz:id = 4 和 id = 2
感谢您的帮助!
如果您使用的是 SQL Server 2012 或更高版本,您可以使用函数 LEAD
and LAG
来连接上一个和下一个数据。不幸的是,这些功能只能在 SELECT
或 ORDER BY
子句中使用,因此您需要使用子查询来获取所需的数据:
SELECT t.trader, t.current_price - t.previous_price as difference
FROM (
SELECT
a.trader,
a.price as current_price,
LAG(a.price) OVER(PARTITION BY a.trader ORDER BY a.ID) as previous_price,
LEAD(a.price) OVER(PARTITION BY a.trader ORDER BY a.ID) as next_price
FROM sale a
) t
WHERE t.next_price IS NULL
在您的子查询中,您为上一个和下一个值创建了额外的列。然后在您的主查询中,您仅过滤下一个价格为 NULL 的这些行 - 这表明这是特定交易者的最后一行。