Distinct rows with non-null values taking precedence over nulls

佐手、 提交于 2021-01-28 14:01:10

问题


I have two duplicated two rows except one column of the row has null value and another one has some value. For example

CarName  Owner  PreviousOwner
Honda    XXX    YYYYY
Honda    XXX    
Nissan   ZZZ    AAAA
Nissan   ZZZ    
BMW      BBB
Benz     CCC    DDD

OUTPUT should be

Honda    XXX    YYYYY
Nissan   ZZZ    AAAA
BMW      BBB
Benz     CCC    DDD

Can you please help me to write a query for this.


回答1:


Check this

select CarName, Owner, max(PreviousOwner)
from t
group by CarName, Owner



回答2:


If we were to order the records such that the previous owner with a value came on top, then all you would have to do is select the topmost row. In order to achieve that, I used the row_number() along with ordering of previous_owner. Please see below:

select carname, owner, previous_owner from 
(select cars.*, rowid, row_number() over (partition by carname, owner order by 
previous_owner) rid 
from cars) 
where rid <=1;



回答3:


One way is:

select t.CarName, t.Owner, r.PreviousOwner
from (select Carname, max(previousowner)
       from test 
       group by carname) r
inner join test t 
on t.carname = r.carname and t.previousowner = r.previousowner
group by t.CarName, t.Owner, r.PreviousOwner;


来源:https://stackoverflow.com/questions/54874089/distinct-rows-with-non-null-values-taking-precedence-over-nulls

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!