I have a simple problem , Although i believe its simple , am not able to figure out the same.
Consider i have the below table with exactly same data as given below :
CREATE TABLE #temp ( link varchar(255), number INT, fname varchar(255) ) insert into #temp VALUES ('abc',1,'f1') insert into #temp VALUES ('abc',2,'f2') insert into #temp VALUES ('abc',3,'f3') insert into #temp VALUES ('abc',4,'f6') insert into #temp VALUES ('abc',10,'f100') insert into #temp VALUES ('abe',-1,'f0') insert into #temp VALUES ('abe',1,'f1') insert into #temp VALUES ('abe',2,'f2') insert into #temp VALUES ('abe',3,'f3') insert into #temp VALUES ('abe',4,'f6') insert into #temp VALUES ('abe',20,'f200') insert into #temp VALUES ('cbe',-1,'f0') insert into #temp VALUES ('cbe',1,'f1') insert into #temp VALUES ('cbe',2,'f2') insert into #temp VALUES ('cbe',3,'f3')
Now for a given link , i need to get the max ‘number’ and the corresponding ‘fname’ which has the max ‘number’ for the given ‘link’.
1)Ex : if link is ‘abc’ , output should be
abc, 10, f100
2)Ex : if link if ‘abe’ , Output should be
abe, 20, f200
3)Now link can be also given as a pattern , like (link like ‘ab%’) , so output should be
abc, 10, f100
abe, 20, f200
4)if (link like ‘cb%’) , so output should be
cbe, 3, f3
Any help in writing this group by query. I have a solution using CAST and string concat like below , but that seems to be in-efficient.
select link,number,fname from #temp
where link like 'ab%' and link+'_'+CAST(number AS varchar(255))
in (select link+'_'+CAST(MAX(number) AS varchar(255)) from #temp
group by link)
Thanks..
Using a self join:
Using a CTE and ROW_NUMBER (SQL Server 2005+):