下面就以3列的最後一個非空值結合了迂迴的方式:
-- Using a table variable for test data
declare @Test table (tableId int identity(1,1), id int, name varchar(100), age int, tel varchar(30));
insert into @Test (id, name, age, tel) values
(1,'Frank',40,null),
(1,null,50,'7834xx'),
(1,'Alex',null,null),
(1,null,20,null),
(2,'James',null,'4121xx');
select n.id, n.name, a.age, t.tel
from (
select top(1) with ties id, name
from @Test
where name is not null
order by row_number() over (partition by id order by tableId desc)
) n
inner join (
select top(1) with ties id, age
from @Test
where age is not null
order by row_number() over (partition by id order by tableId desc)
) a on (n.id = a.id)
inner join (
select top(1) with ties id, tel
from @Test
where tel is not null
order by row_number() over (partition by id order by tableId desc)
) t on (n.id = t.id);
-- or by re-using a CTE
;with CTE AS (
select * ,
row_number() over (partition by id, iif(name is not null,1,0) order by tableId desc) as rn_name,
row_number() over (partition by id, iif(age is not null,1,0) order by tableId desc) as rn_age,
row_number() over (partition by id, iif(tel is not null,1,0) order by tableId desc) as rn_tel
from @Test
)
select n.id, n.name, a.age, t.tel
from CTE n
join CTE a on (a.id = n.id and a.age is not null and a.rn_age = 1)
join CTE t on (t.id = n.id and t.tel is not null and t.rn_tel = 1)
where (n.name is not null and n.rn_name = 1);
結果:
╔════╦══════╦═════╦════════╗
║ id ║ name ║ age ║ tel ║
╠════╬══════╬═════╬════════╣
║ 1 ║ Alex ║ 20 ║ 7834xx ║
╚════╩══════╩═════╩════════╝
你嘗試過什麼嗎?堆棧溢出不是免費的代碼寫入服務。 –
首先嚐試以正確的方式保存數據。聚合會達到目的,但這不是解決方案,表本身是問題 – GauravKP