Thursday, November 14, 2013

Group by one column and select more than one column Sql query

Some times you required to select multiple columns but doesn't required to group by more than on column, to achieve this follow the example given below:

declare @tempTbale table(ID int identity(1,1),col1 varchar(20),col2 varchar(20),col3 varchar(20),col4 varchar(20),col5 int)
insert into @tempTbale values('h','x','y','p',10)
insert into @tempTbale values('k','m','y','p',10)
insert into @tempTbale values('l','n','y','p',40)
insert into @tempTbale values('h','x','y','q',30)
insert into @tempTbale values('h','x','y','r',20)
insert into @tempTbale values('s','u','y','r',10)

select MIN(col1) as col1,MIN(col2) as col2,MIN(col3) as col3,col4,SUM(col5) as col5 from @tempTbale
group by col4

No comments: