合并两个查询,同时保留所有结果

Combine two queries while keeping all the results

我有两个表,我必须合并结果,将所有结果保存在一个数据集中。

我尝试了各种连接,但没有结果 returns。

我需要查询 SQL 服务器和 MS Access。

示例:

TAB_A

+---------------------+------+
|       DATAORA       |  P1  |
+---------------------+------+
| 02/05/2020 15:00:30 | 100  |
| 02/05/2020 15:15:30 | 200  |
| 02/05/2020 15:30:30 | 300  |  
| 02/05/2020 15:45:30 | NULL |
| 02/05/2020 16:00:30 | 500  |
+---------------------+------+

TAB_B

+---------------------+------+
|         ORA         |  P2  |
+---------------------+------+
| 02/05/2020 15:00:30 | 600  |
| 02/05/2020 15:16:30 | 700  |
| 02/05/2020 15:40:30 | NULL |  
| 02/05/2020 15:45:30 | 800  |
| 02/05/2020 15:59:30 | 900  |
+---------------------+------+

结果

+---------------------+------+------+
|       DATAORA       |  P1  |  P2  |
+---------------------+------+------+
| 02/05/2020 15:00:30 | 100  | 600  |
| 02/05/2020 15:15:30 | 200  | NULL |
| 02/05/2020 15:16:30 | NULL | 700  |
| 02/05/2020 15:30:30 | 300  | NULL |
| 02/05/2020 15:40:30 | NULL | NULL |
| 02/05/2020 15:45:30 | NULL | 800  |
| 02/05/2020 15:59:30 | NULL | 900  |
| 02/05/2020 16:00:30 | 500  | NULL |
+---------------------+------+------+

枢轴如何

例子

Select *
 From  (
        Select DATAORA,P1,Item = 'P1' From Tab_A
        Union All
        Select ORA    ,P2,Item = 'P2' From Tab_B
       ) src
 Pivot (sum(P1) for Item in ([P1],[P2]) ) pvt

您描述的是full join。如果你的 RDBMS 支持,那么逻辑是:

select time, a.p1, b.p2
from ( ... query A ...) a
full join ( ... query B ...) b using(time)

请注意,这假设两个查询 return 一个名为 time 的列,这简化了语法。

如果你的数据库不支持full joins,你可以使用union all和聚合:

select time, max(p1) p1, max(p2) p2
from (
    select time, p1, null from (... query A ...)
    union all select time, p1, null from (... query B ...)
) t
group by time