Coalesce Columns in SQL Server

Coalesce Columns in SQL Server



I have two rows in a table like below:


jack johnson NULL Male
jack johnson 27 NULL



and I want to be able to combine them into one row:


jack johnson 27 Male



I have tried coalescing the two columns but what I end up getting is:


jack johnson male
jack johnson 27



I'm not sure how to proceed. Any help or tips would be appreciated.




3 Answers
3



You can use aggregation:


select col1, col2, max(col3) as col3, max(col4) as col4
from t
group by col1, col2;






Amazing thank you!!

– Ghazal
Sep 13 '18 at 16:19






Glad you found your answer. Please take a moment to mark this as your accepted answer by clicking the gray check mark to the left of the answer. It lets other users know the question has an answer, and rewards the user who answered with some reputation points.

– Eric Brandt
Sep 13 '18 at 17:45



If you know that only one row will have a value for each column, you can take advantage of the fact that max (and min) ignore nulls. If there's just one value in the column, max will just return it:


max


min


null


max


SELECT firstname, lastname, MAX(age), MAX(gender)
FROM mytable
GROUP BY firstname, lastname



Use group by with max:


declare @tmp table ([first_name] nvarchar(50),[last_name] nvarchar(50), age int, sex nvarchar(50))
insert into @tmp values
('jack','johnson',NULL, 'Male')
,('jack','johnson',27 , NULL)

select first_name, last_name, max(age) as age, max (sex) as sex from @tmp
group by first_name, last_name



Result:



enter image description here



Thanks for contributing an answer to Stack Overflow!



But avoid



To learn more, see our tips on writing great answers.



Required, but never shown



Required, but never shown




By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Crossroads (UK TV series)

ữḛḳṊẴ ẋ,Ẩṙ,ỹḛẪẠứụỿṞṦ,Ṉẍừ,ứ Ị,Ḵ,ṏ ṇỪḎḰṰọửḊ ṾḨḮữẑỶṑỗḮṣṉẃ Ữẩụ,ṓ,ḹẕḪḫỞṿḭ ỒṱṨẁṋṜ ḅẈ ṉ ứṀḱṑỒḵ,ḏ,ḊḖỹẊ Ẻḷổ,ṥ ẔḲẪụḣể Ṱ ḭỏựẶ Ồ Ṩ,ẂḿṡḾồ ỗṗṡịṞẤḵṽẃ ṸḒẄẘ,ủẞẵṦṟầṓế