sql-server - 及时返回以查看 SQL Server 中是否存在值
问题描述
我需要在 SQL 中创建一个查询,该查询将采用记录集(select 语句)并返回发生的价格变化的最后一个值。所以像这种情况。
--Create a TableVariable(only in memory)
Declare @CarPrices Table (testid int, car nvarchar(50),price
nvarchar(50),PricingDate date)
--Insert Data
insert into @CarPrices (testid, car, price, PricingDate) values (1, 'Ford',
'1.00043', '05/15/2018')
insert into @CarPrices (testid, car, price, PricingDate) values (2,
'Chevy','1.00043', '05/15/2018')
insert into @CarPrices (testid, car, price, PricingDate) values (3, 'Chevy',
NULL, '05/16/2018')
insert into @CarPrices (testid, car, price, PricingDate) values (4, 'Ford',
NULL, '05/16/2018')
insert into @CarPrices (testid, car, price, PricingDate) values (5, 'Ford',
'1.0053', '05/17/2018')
insert into @CarPrices (testid, car, price, PricingDate) values (6, 'Chevy',
NULL, '05/17/2018')
insert into @CarPrices (testid, car, price, PricingDate) values (7, 'Chevy',
NULL, '05/18/2018')
insert into @CarPrices (testid, car, price, PricingDate) values (8, 'Ford',
NULL, '05/18/2018')
insert into @CarPrices (testid, car, price, PricingDate) values (9, 'Audi',
'10.0003', '05/18/2018')
目标:查看数据集,获取最新的汽车日期和价格
任何想法或任何尝试。我没有足够小的数据集来使用,所以我使用的是汽车、定价和日期,这本质上是我将在更大范围内做的事情。有什么想法吗?也许是 IIF 语句的复杂案例语句?我真的不知道从哪里开始。
解决方案
对同一辆车的先前非空价格使用外部应用可以解决问题
declare @T table (id int identity(1,1) primary key, Car varchar(30), [day] date, price money);
insert into @T (Car, [day], price) values
('ford', '2018-05-13',5003.00),
('Chevy','2018-05-13',8003.00),
('ford', '2018-05-14',5004.00),
('Chevy','2018-05-14',null),
('ford', '2018-05-15',null),
('Chevy','2018-05-15',8005.00);
select Car, [day], price, coalesce(price, prevPrice) as CorrectedPrice
from @T t1
outer apply
(
select top 1 price as prevPrice
from @T t2
where t2.Car = t1.Car
and t2.[day] < t1.[day]
and datediff(day,t2.[day],t1.[day]) <= 5 -- only the previous 5 days
and t1.price is null
and t2.price is not null
order by t2.[day] desc
) q1
order by t1.Car, t1.[day];
结果:
Car day price CorrectedPrice
----- ---------- ------- --------------
Chevy 2018-05-13 8003,00 8003,00
Chevy 2018-05-14 NULL 8003,00
Chevy 2018-05-15 8005,00 8005,00
ford 2018-05-13 5003,00 5003,00
ford 2018-05-14 5004,00 5004,00
ford 2018-05-15 NULL 5004,00
推荐阅读
- apache-kafka - 如何使用 Jmeter 加载测试 Kafka 主题
- python - 正则表达式,在另一个之前和之后提取单词
- android - 无法启动活动 ComponentInfo java.lang.RuntimeException:无法创建 webview
- bash - 如何编辑此代码以显示多个文件(它目前适用于 1 个文件)?
- apache - 在共享主机中部署后“身份验证失败”
- javascript - 在 setState 的回调中调用 setState 会生成一个奇怪的错误,该错误会阻止 onChange 更新输入的值
- swiftui - 从列表中关闭 SwiftUI 模态“工作表”
- javascript - 如何从“1823917+3”之类的字符串中提取整数/浮点数和符号?
- ios - Swift 4 中的 SideMenu 功能
- spring - Spring 应用程序到 Spring 引导迁移-“没有可用的 'javax.persistence.EntityManagerFactory' 类型的合格 bean”