如何联接两个表,并且仅从第二个表中获取值(如果存在)?

时间:2018-12-02 05:46:48

标签: sql sql-server tsql join select

TABLE1只有1列和28行。每行是过去28天的DateTime。

TABLE2是2列:DateTime和Value。行数是不可预测的,但是DateTime将始终是过去28天。

我想将这两个表连接起来,以使结果表具有2列(日期时间和值)和28行,最近28天中的每一行。如果存在,则从TABLE2中获取Value列;如果不存在,则从NULL或-1中获取。

最好的方法是什么?

表1 (28x1)

DATE
11/3/2018 12:00:00AM
11/4/2018 12:00:00AM
11/5/2018 12:00:00AM
...
...
11/30/2018 12:00:00AM

表2 (4x2)

DATE                  | VALUE
----------------------+-------
11/3/2018 12:00:00AM  |  45
11/21/2018 12:00:00AM |  78
11/22/2018 12:00:00AM |  85
11/29/2018 12:00:00AM | 103

预期结果(28x2)

DATE                 | VALUE
---------------------+-------
11/3/2018 12:00:00AM | 45
11/4/2018 12:00:00AM | null
11/5/2018 12:00:00AM | null
...
...
11/20/2018 12:00:00AM | null
11/21/2018 12:00:00AM | 78
11/22/2018 12:00:00AM | 85
11/23/2018 12:00:00AM | null
...
11/29/2018 12:00:00AM | 103
11/30/2018 12:00:00AM | null

到目前为止,我尝试过的任何JOIN都行不通,因为我必须连接到列上,并且唯一的共同列是DateTime&,它消除了没有值的行。

3 个答案:

答案 0 :(得分:2)

关于列名称的建议,不要在日期或日期时间等列中使用sqlserver的保留字。

给出下面的示例可以解决您的问题:(如上述建议,您需要左联接)

declare @table1 table( dateColumn datetime)
declare @table2 table( dateColumn datetime, value int)

--insert into @table1 values ('11/3/2018 12:00:00AM' ),( '11/4/2018 12:00:00AM'), ('11/5/2018 12:00:00AM')
--To test I insert current month's all dates in @table1
Declare @year int = 2018, @month int = 11;
WITH numbers
as
(
    Select 1 as value
    UNion ALL
    Select value + 1 from numbers
    where value + 1 <= Day(EOMONTH(datefromparts(@year,@month,1)))
)

Insert into @Table1  
SELECT datefromparts(@year,@month,numbers.value) Datum FROM numbers

insert into @table2 values ('11/3/2018 12:00:00AM' , 45), ('11/21/2018 12:00:00AM', 78), ('11/22/2018 12:00:00AM', 85), ('11/29/2018 12:00:00AM', 103)

SELECT    t1.dateColumn, t2.[value]
FROM    @table1  t1
LEFT JOIN @table2 t2 ON t1.dateColumn = t2.dateColumn

答案 1 :(得分:1)

这是发明left join的目的:

SELECT    t1.[datetime], t2.[value]
FROM      t1
LEFT JOIN t2 ON t1.[datetime] = t2.[datetime]

答案 2 :(得分:0)

希望这可以解决您的问题。

SELECT    t1.[datetime], t2.[value]
FROM      t1
LEFT JOIN t2 ON cast(t1.[datetime] as date) = cast(t2.[datetime] as date)