SQL Server合并两个表并计算缺失值

时间:2018-09-08 11:10:34

标签: sql-server

我有一个包含日期的表T1和一个包含日期和值的表R2。 我想进行查询以检索R2的日期和值,并将其与需要从表R2中查找值的T1日期进行分组

T1

Start Date
-----------------------
2018-08-09 09:42:00.000
2018-08-09 09:46:00.000
2018-08-09 09:48:00.000

R2

Start Date             | Value
-----------------------|-------
2018-08-09 09:40:00.000|1
2018-08-09 09:43:00.000|2
2018-08-09 09:44:00.000|3

结果

Start Date             | Value|Original|
-----------------------|----------------
2018-08-09 09:40:00.000|1     |yes     |
2018-08-09 09:43:00.000|2     |yes     |
2018-08-09 09:44:00.000|3     |yes     |
2018-08-09 09:42:00.000|1     |no      | --> Value found in R2 table (first value before the date)
2018-08-09 09:46:00.000|3     |no      | --> Value found in R2 table (first value before the date)
2018-08-09 09:48:00.000|3     |no      | --> Value found in R2 table (first value before the date)

预先感谢

1 个答案:

答案 0 :(得分:1)

一个选项,也许不是性能最高的,但是应该在任何版本的SQL Server上都可以使用,它使用相关子查询在T1中查找最近的开始日期,该日期小于{{ 1}}。

WITH cte AS (
    SELECT
        t1.StartDate,
        (SELECT TOP 1 t2.Value FROM R2 t2
         WHERE t2.StartDate < t1.StartDate ORDER BY t2.StartDate DESC) Value,
        'No' AS Original
    FROM T1 t1
)

SELECT StartDate, Value, 'Yes' AS Original FROM R2
UNION ALL
SELECT StartDate, Value, Original FROM cte
ORDER BY Original DESC, StartDate;

Demo