Luk*_*uke 5 sql sql-server-2008
我在表中有一些看起来与此类似的数据:
Item Date Price A 8/29/2012 $3 B 8/29/2012 $23 C 8/29/2012 $10 A 8/30/2012 $4 B 8/30/2012 $25 C 8/30/2012 $11 A 8/31/2012 $3 B 8/31/2012 $22 C 8/31/2012 $8 A 9/01/2012 $3 B 9/01/2012 $26 C 9/01/2012 $9 A 9/02/2012 $3 B 9/02/2012 $24 C 9/02/2012 $9
我需要编写一个查询,确定A的价格自2012年8月30日以来没有变化,项目C的价格自2012年9月1日起没有变化,并返回两者的经过天数(我们'正在寻找价格不变的物品).我不能使用CTE,或游标,或单独创建临时表(select into等),因为这个sql需要运行的Web报表工具的限制.我只能使用'基本'单通道选择查询(子查询将工作).有没有人对如何实现这一点有任何狡猾的想法?
我的第一次尝试是按物品和价格进行分组,其中价格与最新价格相同having count > 2,确定最小日期并在最短日期和最近日期之间进行约会.但是,这仅仅标识了该价格的第一个实例,它没有考虑可能具有不同价格的任何后续行.希望有道理.
我给出了两种类型的年龄,并说明了表中仅存在一次的项目(它们没有旧日期)。请让我们知道这有多接近。
更新:我必须更正“PriceAgeToNow”中的日期计算,并且我还尝试过滤掉仅具有 1 天新价格的记录。这是SQL Fiddle。
-- Get the age of the current price
select *
, datediff(d, c.OldDate, getdate()) as PriceAgeToNow
, datediff(d, c.OldDate, c.NewDate) as PriceAgeToNewestDate
from (
select *
-- Get max date of former price
, isnull(
(select max(Date) from PricingTable where Item = b.Item and Date < b.NewDate and Price != b.NewPrice), b.NewDate
) as OldDate
from (
-- Get current price
select *
, (select Price from PricingTable where Item = a.Item and Date = a.NewDate) as NewPrice
from (
-- Get current date
select Item
, max(Date) as NewDate
from PricingTable
group by Item
) a
) b
) c
-- Attempt to filter out price changes that have only lasted 1 day
where datediff(d, c.OldDate, c.NewDate) > 1
Run Code Online (Sandbox Code Playgroud)