我有一个表格,每天显示一个产品价格。一个产品有3个价格:批发价,数量和清仓价。
该表每天都用当前价格进行更新,大多数日子没有变化。但是,我想选择其中一个值已更改的行,而我正在努力寻求构想。我试过了一个小组,但是因为价格涨跌,这行不通。
select date_entered,
WholeSale,
Volume,
Clearance
FROM pricetable
where product = 'TANGO'
order by date_entered desc
以上内容从表格中为已设置产品选择所有行。
如何做到这一点,所以只能进行更改,批发,数量或清仓的行。
任何帮助表示赞赏。
答案 0 :(得分:1)
该问题最初是带标签的SQL-SERVER(无版本)。这适用于SQL Server 2012 +:
使用lag()
。像这样:
select pt.*
from (select pt.*,
lag(wholesale) over (partition by product
order by date_entered) as prev_wholesale,
lag(volume) over (partition by product
order by date_entered) as prev_volume,
lag(clearance) over (partition by clearance
order by date_entered) as prev_clearance
from pricetable
where product = 'TANGO'
) pt
where (prev_wholesale is null or prev_wholesale <> wholesale) or
(prev_volume is null or prev_volume <> volume) or
(prev_clearance is null or prev_clearance <> clearance)
order by date_entered desc;
答案 1 :(得分:1)
select p1.date_entered,
p1.WholeSale,
p1.Volume,
p1.Clearance
FROM pricetable p1
CROSS APPLY
--cross apply to most recent prior record
(SELECT TOP 1 *
FROM pricetable p2
where p1.product = p2.product
and p2.date_entered < p1.date_entered
order by p2.date_entered desc) CA
where p1.product = 'TANGO'
and (p1.wholesale != CA.wholesale or p1.volume != CA.volume or p1.clearence != CA.clearence)
order by p1.date_entered desc
答案 2 :(得分:0)
将每一行的值与前一天的值进行比较:
SELECT * FROM pricetable p WHERE (p.product = 'TANGO') AND
(
(p.WholeSale <> (SELECT WholeSale FROM pricetable WHERE product = 'TANGO' AND date_entered = dateadd(day, -1, p.date_entered))
OR
(p.Volume <> (SELECT Volume FROM pricetable WHERE product = 'TANGO' AND date_entered = dateadd(day, -1, p.date_entered))
OR
(p.Clearance <> (SELECT Clearance FROM pricetable WHERE product = 'TANGO' AND date_entered = dateadd(day, -1, p.date_entered))
)