按日期联接表,但多隔一天对齐一个表

时间:2018-11-14 16:09:45

标签: sql sql-server tsql datetime

我下面有两个表:

表A

+------------+-------+
|    Date    | Value |
+------------+-------+
| 11-08-2018 |   2.3 |
| 11-09-2018 |   4.3 |
| 11-12-2018 |   2.9 |
| 11-13-2018 |   3.9 |
+------------+-------+

表B

+------------+---------+
|    Date    |  Value  |
+------------+---------+
| 11-07-2018 |   -6.99 |
| 11-08-2018 | 12.3333 |
| 11-09-2018 |   14.22 |
| 11-12-2018 |    3.66 |
+------------+---------+

我需要在“日期”字段中加入他们,但是我想加入他们,所以我得到如下所示的结果(即,我想在表B的日期字段中添加一天,但也忽略了周末)

+------------+---------+---------+
|    Date    | Value A | Value B |
+------------+---------+---------+
| 11-08-2018 |     2.3 |   -6.99 |
| 11-09-2018 |     4.3 |  12.333 |
| 11-12-2018 |     2.9 |   14.22 |
| 11-13-2018 |     3.9 |    3.66 |
+------------+---------+---------+

如何最好地实现这一目标?

3 个答案:

答案 0 :(得分:3)

假设您想加入周一和上周五:

SELECT *
FROM tablea
INNER JOIN tableb ON DATEADD(DAY, IIF(DATENAME(WEEKDAY, tablea.Date) = 'Monday', -3, -1), tablea.Date) = tableb.Date

答案 1 :(得分:1)

定义一个将日期添加到跳过周末的日期的函数:

create function dbo.udf_AddWorkingDays(@dateToIncrement as date, @daysToAdd as int)
returns datetime
as
begin
    SET @dateToIncrement = dateadd(d, @daysToAdd, @dateToIncrement)

    --skip sundays
    IF datename(DW, @dateToIncrement) = 'sunday'   
        SET @dateToIncrement = dateadd(d, 1, @dateToIncrement)

    --skip saturdays
    IF datename(DW, @dateToIncrement) = 'saturday' 
        SET @dateToIncrement = dateadd(d, 2, @dateToIncrement)

    return cast(@dateToIncrement AS datetime)
end

在联接条件下使用这些函数:

declare  @tableA table ([Date] date , [Value] decimal(10,2))
declare  @tableB table ([Date] date , [Value] decimal(10,2))
insert into @tableA values
 ('2018-11-08', 2.3)
,('2018-11-09', 4.3)
,('2018-11-12', 2.9)
,('2018-11-13', 3.9)

insert into @tableB values
 ('2018-11-07', -6.99  )
,('2018-11-08', 12.3333)
,('2018-11-09', 14.22  )
,('2018-11-12', 3.66   )

select A.[Date], A.[Value], B.[Value]
from @tableA A
inner join @tableB B on A.[Date] = dbo.udf_AddWorkingDays(B.[Date], 1)

结果:

enter image description here

答案 2 :(得分:0)

您可以相应地修改加入条件

SELECT TableA.Date, TableA.Value as [Value A], TableB.Value as [Value B]
FROM TableB
JOIN TableA
ON TableA.Date = DATEADD(day, 1, TableA.Date)