sql - 用另一个表 SQL Server 中的值替换列中的 NA

标签 sql sql-server join sql-update inner-join

这是我第一次在 stack overflow 上发帖,我知道以前也有人问过类似的问题,所以我提前道歉。但是,无论其他论坛中提供的解决方案如何,我似乎都无法解决这个问题。

我在 SQL Server 中有两个表,一个包含 Storm 事件信息,另一个包含县信息。它们都包含相同的 county_fips 号码。这些都不包含主键或外键。

我需要用县表中的纬度/经度替换 Storm 事件信息中的 NA。如果没有外键/主键关系,这可能吗?

StormEvent 表如下所示:

ID | Lat | Lon | State_FIPS | County_FIPS 
------------------------------------------
1  |  33 | -88 |    028     |    087
2  |  31 | -98 |    048     |    225
3  |  NA |  NA |    017     |    034
4  | 39  | -100|    020     |    063

等等……

CountyTable 看起来像这样(statefp10,countyfp10 = FIPS;intptlat10,intptlon10 = lat/lon):

  StateFP10 | County_FP10   | State_FP10| intptlat10 | intptlon10
   --------------------------------------------------------------
    1       |  087          | 028       |    33      |  -88
    2       |  225          | 048       |    31      |  -98     
    3       |  034          | 017       |    45      |  -102

等等。

到目前为止,我已尝试使用以下代码来调整 Lat 列,但会有细微的变化:

UPDATE n 
SET n.lat= c.intptlat10
FROM StormEvent n 
INNER JOIN CountyTable c ON n.County_FIPS= c.CountyFP10
WHERE n.LAT = 'NA' 

查询已执行,我被告知有 x 行受到影响,但是当我编写一个 select 语句来检索 StormEvent 表的 Lats 中包含的所有 NA 时,它们还在那里。

如果有人能指出我正确的方向,将不胜感激!再次,如果我以错误的方式解决这个问题,我深表歉意,这是我的第一篇文章,我是 SQL 新手。

最佳答案

假设您实际上不需要设置数据,而只是想在查询时查看纬度/经度数据,您应该可以这样做:

select 
a.ID, 
case a.Lat when 'NA' then b.intptlat10 else a.Lat end as Lat, 
case a.Lon when 'NA' then b.intptlon10 else a.Lon end as Lon, 
a.State_FIPS, 
a.County_FIPS 
from StormEvent a
left join CountyTable b
on a.State_FIPS = b.StateFIPS;

关于sql - 用另一个表 SQL Server 中的值替换列中的 NA,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38511295/

相关文章:

php - Codeigniter - 事件记录 - sql - 复杂连接

sql - 如何将变量从shell脚本传递给sqlplus

sql - 从存储过程将数据插入临时表

c# - 没有对的单独记录

mysql - mysql查询应该是什么来获取存储在同一个表中的一组用户最近添加的消息

MySQL 3个链接表的查询优化

sql - 从 case when 语句返回多行作为逗号分隔值

java.sql.SQLException : Invalid argument(s) in call: getBytes() 异常

sql - 在ms-sql中计算累积和

django - 引用 Django 模板中的用户 ID 显示用户名