sql - SQL 查询按日期更改历史记录
问题描述
我有一个变更历史表如下
+-----+-------------+------------+------------+
| ID | BeforeValue | AfterValue | DateTime |
+-----+-------------+------------+------------+
| 255 | 396 | 400 | 01/01/2017 |
| 255 | 400 | 500 | 15/08/2017 |
| 255 | 500 | 600 | 02/06/2018 |
+-----+-------------+------------+------------+
DECLARE @tabl TABLE (ID int, BeforeValue varchar(20),AfterValue varchar(20), changeDate datetime2(0));
INSERT INTO @tabl (ID, BeforeValue, AfterValue,changeDate) VALUES
(255,'396','400', '01/01/2017'),
(255,'400','500', '08/15/2017'),
(255,'500','600', '06/02/2018');
select * from @tabl
我有另一个表,其中存在交易数据,
DECLARE @output TABLE (ID int, dat datetime2(0));
INSERT INTO @output (ID, dat) VALUES
(255, '07/15/2017'),
(255, '10/29/2018'),
(255, '01/01/2015');
select * from @output
想找出给定时间段的值是多少
例如输出如下
╔═════╦════════════╦══════════════╗
║ id ║ date ║ Desiredvalue ║
╠═════╬════════════╬══════════════╣
║ 255 ║ 15/07/2017 ║ 400 ║
║ 255 ║ 29/10/2018 ║ 600 ║
║ 255 ║ 01/01/2015 ║ 396 ║
╚═════╩════════════╩══════════════╝
请让我知道是否可以使用 SQL 语句,而无需任何存储过程。
解决方案
您可以使用outer apply
:
select o.*, coalesce(t.aftervalue, tfirst.beforevalue) as thevalue
from @output o outer apply
(select top (1) t.aftervalue
from @tab t
where t.id = o.id and t.datetime <= o.date
order by t.datetime desc
) t outer apply
(select top (1) t.beforevalue
from @tab t
where t.id = o.id
order by t.datetime asc
) tfirst;
推荐阅读
- python - 在本地(非 Azure)docker 实例中使用来自 Azure 源的 python 包
- javascript - Webpack configuration in Gatsby, naming conventions
- ios - 'React/RCTBridgeDelegate.h' 文件未找到 React Native 和 XCode
- java - 在 Heroku 上部署 Java Telegram 机器人:无法找到或加载主类
- python - Python:在两个回调之间共享结果
- swift - 在隐式展开可选值时意外发现 nil (UICollectionView)
- java - 如何创建一个 int [](不是 List
) 我的 LinkedList 中的所有对象值? - javascript - 相机在使用 p5.js 的 webview android 中不起作用
- android - Android BroadcastReceiver 仅在使用需要 GPS 的应用时触发
- sas - 导出 SAS 用户数据,包括外部身份