我是sql的新手
我有一个带有[月]的表1,[预测平均值。温度]作为列。我有另一个表2 [月],[实际平均值。温度]作为列。现在对于某些日期,表1中没有可用的记录。在这种情况下,如果我在该表中有可用记录,我想从table2中提取记录。
例如,表1可能具有从2010年4月到12月的记录,例如2010年的记录。表2具有2010年1月1日的记录。我想从表2中提取表1中的mising jan,feb,mar month记录。任何想法。我们正在使用sql server 2008
提前致谢。
答案 0 :(得分:2)
select [month], [forecasted avg. temperature] as temperature from table1
union
select [month], [actual avg. temperature] as temperature from table2
答案 1 :(得分:2)
select
[month], isnull([forecasted avg. temperature], [actual avg. temperature]) as temperature
from
table2 left outer join table1 on table1.[month] = table2.[month]
UPDATE 根据Dems的评论,我更改了查询。原始帖子听起来好像table2包含所有月份的数据,所以我只是切换所以它将从table2中拉出所有记录,而不是FULL JOIN,如果可用于table1,则继续使用ISNULL作为temp。如果table2不包含所有数据,则需要FULL JOIN。
答案 2 :(得分:0)
一种方法是使用外连接查询
的联合Select [month], [forecasted avg. temperature] from Table1
Union
Select [month], [actual avg. temperature] From Table2
outer join Table1 on Table1.[Month] = Table2.Month
Where Table1.Month is null
离开我的头顶,为了Cthulu的缘故,给你的表和列合法的名字。
如果您想在输出上使用更友好的名称,请执行类似
的操作Select ForeCastAvgTemp As [forecasted avg. temperature] From Table1