sql - Merge rows into one row based on condition -


i have table structure similar below

create table #temp(name varchar(10),col1 int,col2 int,col3 int,col4 int,col5 int) 

in case table can have same name repeated other values different

so.

sample values can

insert #temp values('abc',1,0,0,1,1) insert #temp values('abc',1,0,1,1,0) insert #temp values('abc',1,0,1,1,0) insert #temp values('def',0,0,0,1,0) insert #temp values('def',1,0,1,1,1) insert #temp values('def',1,1,0,1,1) 

what trying here select 1 row each name, select column priority has value 1.

so expected result in case

name    col1    col2    col3    col4    col5 abc         1    0      1          1    1 def         1    1      1          1    1 

i have achieved doing below, works absolutely fine. there proper(easy) way of doing this.

select name,         (select top 1 col1         #temp t          t.name=m.name         order col1 desc) col1,          (select top 1 col2         #temp t          t.name=m.name         order col2 desc) col2,          (select top 1 col3         #temp t          t.name=m.name         order col3 desc) col3,          (select top 1 col4         #temp t          t.name=m.name         order col4 desc)as col4,          (select top 1 col5         #temp t          t.name=m.name         order col5 desc) col5 #temp m group name 

it seems me need use max:

select  [name],         max(col1) col1,         max(col2) col2,         max(col3) col3,         max(col4) col4,         max(col5) col5 #temp group [name] 

Comments

Popular posts from this blog

c# - How Configure Devart dotConnect for SQLite Code First? -

java - Copying object fields -

c++ - Clear the memory after returning a vector in a function -