首页 > 解决方案 > 通过在多个字段上连接两个表来创建类似联合 B 的输出结构

问题描述

使用不同名称的两个字段连接两个表不起作用

我有两张桌子,

a:按小时计算的表格

-----------------------------------------
datetime        | customer | pastdemand | levelOfDetail |   
-----------------------------------------
04-01-2019 06:00 | 444111 | 100 | 6 |   
.........   
04-30-2019 18:00 | 444111 | 150 | 6 |   

在这里我可以有两个级别 6 或 24。我只对级别 = 6 感兴趣。表 b:是客户存储的未来值的日志。

-----------------------------------------
forecastdatetime        | custNumber | forecast | dateGenerated   
-----------------------------------------
04-30-2019 18:00 | 444111 | 120 | 04-29-2019 18:00   
..........   
05-01-2019 18:00 | 444111 | 140 | 05-01-2019 18:00   
05-02-2019 18:00 | 444111 | 140 | 05-01-2019 18:00   
05-03-2019 18:00 | 444111 | 140 | 05-01-2019 18:00   
05-04-2019 18:00 | 444111 | 140 | 05-01-2019 18:00   
05-05-2019 18:00 | 444111 | 140 | 05-01-2019 18:00   
........   

查询:

 SELECT a.[datetime],a.customer
  [demand]
  ,b.*

  FROM a
  full outer join b on a.customer=b.custNumber
  and a.datetime=b.forecastdatetime 

我得到的结果看起来像左连接。

----------------------------------------------------
datetime| customer| pastdemand | forecastdatetime|custNumber|forecast| dateGenerated    
-----------------------------------------   

04-01-2019 06:00 | 444111 | 100 | 6 | NULL | NULL | NULL | NULL   
......   
04-30-2019 18:00 | 444111 | 150 | 6 | 04-30-2019 18:00 | 444111 | 120 | 04-29-2019 18:00   

我想根据每个生成日期的 customer=custNumber 和 datetime=forecastdatetime 的匹配,在 A 和 B 中常见的 A + 值中创建 AUB 表。预期结果:

 ----------------------------------------------------
    datetime| customer| pastdemand | forecastdatetime|custNumber|forecast| dateGenerated    
    -----------------------------------------   

    04-01-2019 06:00 | 444111 | 100 | 6 | NULL | NULL | NULL | NULL   
    04-02-2019 06:00 | 444111 | 100 | 6 | NULL | NULL | NULL | NULL   
    ......   
    04-30-2019 18:00 | 444111 | 150 | 6 | 04-30-2019 18:00 | 444111 | 120 | 04-29-2019 18:00   
    NULL | NULL |NULL | NULL | 05-01-2019 18:00 | 444111 | 140 | 05-01-2019 18:00   
    NULL | NULL |NULL | NULL | 05-02-2019 18:00 | 444111 | 140 | 05-01-2019 18:00   
    NULL | NULL |NULL | NULL | 05-03-2019 18:00 | 444111 | 140 | 05-01-2019 18:00   
    NULL | NULL |NULL | NULL |  ..........

正如您所注意到的,我没有得到表 B 中在 A 中不常见的部分。我意识到对于使用联合,字段名称需要相同,在这种情况下,它们不是。很乐意工作

标签: sqlsql-server

解决方案


在阅读了您的问题和您对评论部分的想法之后,似乎该问题与SQL JOIN语法无关。问题与您为列所做的选择调用有关 -

SELECT * FROM a
FULL OUTER JOIN b ON a.customer = b.custNumber
and a.datetime = b.forecastdatetime 

所做的更改是检索所有列,匹配和不匹配使用select * ...


推荐阅读