首页 > 解决方案 > 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 语句,而无需任何存储过程。

标签: sqlsql-server

解决方案


您可以使用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;

推荐阅读