SQL使用IIF填充空白
我有两列和几个类似的数据SQL使用IIF填充空白,sql,sql-server,Sql,Sql Server,我有两列和几个类似的数据 sms_type ID fullname incoming 2036037 NULL outgoing 2036037 Jason Sayre 如果ID列匹配,我喜欢用相同的名称(Jason Sayre)填充NULL in fullname列 谢谢。您可以使用coalesce()和窗口函数: select t.*, coalesce(fullname, m
sms_type ID fullname
incoming 2036037 NULL
outgoing 2036037 Jason Sayre
如果ID列匹配,我喜欢用相同的名称(Jason Sayre)填充NULL in fullname列谢谢。您可以使用
coalesce()
和窗口函数:
select t.*,
coalesce(fullname, max(fullname) over (partition by id)) as imputed_fullname
from t;
您可以尝试以下内部联接查询
create table MyTable(sms_type varchar(20)
, ID float
, fullname varchar(50))
insert into MyTable values
('incoming', 2036037, NULL),
('outgoing', 2036037, 'Jason Sayre')
SELECT MyTable.sms_type
,MyTable.ID
,ISNULL(MyTable.fullName, tblname.fullName) AS Name
FROM (
SELECT ID
,max(fullname) AS fullName
FROM MyTable
GROUP BY ID
) tblname
INNER JOIN MyTable ON MyTable.ID = tblName.ID
如果你碰巧在寻找更新,那么戈登的答案有点扭曲(+1) 示例
;with cte as (
Select *
,NewValue =max(fullname) over (partition by ID)
From YourTable
)
Update cte Set FullName=NewValue
Where FullName is null -- Where is optional
sms_type ID fullname
incoming 2036037 Jason Sayre
outgoing 2036037 Jason Sayre
更新后的表格
;with cte as (
Select *
,NewValue =max(fullname) over (partition by ID)
From YourTable
)
Update cte Set FullName=NewValue
Where FullName is null -- Where is optional
sms_type ID fullname
incoming 2036037 Jason Sayre
outgoing 2036037 Jason Sayre
出现错误“关键字“over”附近的语法不正确”。@Tsang不应该出现错误。请勾选“警告:通过聚合或其他集合操作消除空值”