我尝试在SQL中使用完全外连接组合两个不同的表,但无法确定我的SQL查询返回空值的原因。下面的SQL代码根据对象和日期结合表1和表2:
SELECT Table1.Date_T1, Table1.Object_T1, Table1.Price_T1, Table2.Price_T2
FROM Table1
LEFT JOIN Table2 ON Table1.Object_T1 = Table2.Object_T2
AND Table1.Date_T1=Table2.Date_T2
UNION
SELECT Table1.Date_T1, Table1.Object_T1, Table1.Price_T1, Table2.Price_T2
FROM Table1
RIGHT JOIN Table2 ON Table1.Object_T1 = Table2.Object_T2
AND Table1.Date_T1=Table2.Date_T2;
表的内容可见here,以及我尝试创建的结果的示例,以及查询的实际结果。查询不包括仅存在于表2中的值,而不包括表1。
有关如何调整查询以获取每行的相应日期和对象名称的任何建议将不胜感激!
答案 0 :(得分:0)
也许您正在寻找coalesce函数,它返回列表的第一个非null值:
coalesce (v1,v2,v3)
- returns v1 if not null
- otherwise returns v2 if not null
...
- otherwise returns v3
select
coalesce(t1.date,t2.date) date_t12,
coalesce(t1.object,t2.object) object_t12,
t1.price_t1,
t2.price_t2
from table1 t1
left join table2 t2
on t1.date=t2.date and t1.object=t2.object
答案 1 :(得分:0)
错误是,您在Union之后的查询中选择了table1而不是table2中的列。
我选择了table2中的列,并将其重命名为table1中指定的列,以便使其能够将table2中的列追加到table1中。
如果您不想使用Union语句,也可以使用Full outer join
在单个连接语句中获取结果。但是,您需要使用Coalesce
语句并根据您的要求重命名列
试试这个: -
SELECT Table1.Date_T1, Table1.Object_T1, Table1.Price_T1, Table2.Price_T2
FROM Table1
LEFT JOIN Table2 ON Table1.Object_T1 = Table2.Object_T2
AND Table1.Date_T1=Table2.Date_T2
UNION
SELECT Table2.Date_T2 as Date_T1, Table2.Object_T2 AS Object_T1,
Table1.Price_T1, Table2.Price_T2
FROM Table1
RIGHT JOIN Table2 ON Table1.Object_T1 = Table2.Object_T2
AND Table1.Date_T1=Table2.Date_T2;
答案 2 :(得分:0)
我认为正确答案是India.Rocket。只是为了清楚起见,我认为它应该可以帮助你理解你是否只是重命名前两列(在第二个查询中没有必要这样做,UNION之后的那个):
SELECT Table1.Date_T1 AS DATE_X, Table1.Object_T1 AS OBJECT_X, Table1.Price_T1, Table2.Price_T2
FROM Table1
LEFT JOIN Table2 ON Table1.Object_T1 = Table2.Object_T2
AND Table1.Date_T1=Table2.Date_T2
UNION
SELECT Table2.Date_T2, Table2.Object_T2, Table1.Price_T1, Table2.Price_T2
FROM Table1
RIGHT JOIN Table2 ON Table1.Object_T1 = Table2.Object_T2
AND Table1.Date_T1=Table2.Date_T2;
答案 3 :(得分:0)
而不是多个连接和联合,使用直接使用coalesce函数的完全连接。使用COALESCE,如果Table1值为null,则可以显示相应的Table2值
SELECT COALESCE(Table1.Date_T1,Table2.Date_T1),
COALESCE(Table1.Object_T1,Table2.Object_T1), Table1.Price_T1, Table2.Price_T2
FROM Table1
FULL JOIN Table2 ON Table1.Object_T1 = Table2.Object_T2
AND Table1.Date_T1=Table2.Date_T2
答案 4 :(得分:0)
在
组中使用派生联合表select
x.[Date]
,x.[Object]
,sum(x.[Price T1]) [PriceT1]
,sum(x.[Price T2]) [PriceT2]
from
(
SELECT Table1.Date_T1 [Date], Table1.Object_T1 [Object], Table1.Price_T1 [Price T1], 0 [Price T2]
FROM Table1
union
SELECT Table2.Date_T1 [Date], Table2.Object_T1 [Object], 0 [Price T1], Table2.Price_T2 [Price T2]
FROM Table2
) x
group by
x.[Date],x.[Object]