SQL Server Simple Group by query
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:
SELECT x.link,
x.number,
x.fname
FROM #temp x
JOIN (SELECT t.link,
MAX(t.number) AS max_number
FROM #temp t
GROUP BY t.link) y ON y.link = x.link
AND y.max_number = x.number
Using a CTE and ROW_NUMBER (SQL Server 2005+):
WITH cte AS (
SELECT x.link,
x.number,
x.fname,
ROW_NUMBER() OVER(PARTITION BY x.link
ORDER BY x.number DESC) rank
FROM #temp x)
SELECT c.link,
c.number,
c.fname
FROM cte c
WHERE c.rank = 1
精彩评论