user1295053
user1295053

Reputation: 303

SQL Query to select top 2 for each value

I have a table with 3 columns, the data in column1 has repeating values and column 3 has totals, what I'd like to do is to return the top 2 totals for each value in column 1.

My query to create this table is below:

SELECT service,name, total
  FROM [test].[dbo].[TestTable]
  join test1.dbo.service
  on substring(servan,0,4)=servicebn
  where substring(servan,0,4)=servicebn and name <> testname
group by service,name,total
order by service,total desc

any help would be much appreciated

Upvotes: 1

Views: 320

Answers (1)

John Woo
John Woo

Reputation: 263683

if you are using SQL Server 2005+, you can use Common Table Expression and Window Function.

WITH recordsList
AS
(
    SELECT  service, name, total,
            DENSE_RANK() OVER (PARTITION BY service 
                                ORDER BY total DESC) rn
    FROM    [test].[dbo].[TestTable]
            INNER join test1.dbo.servd
                on substring(servan,0,4)=servicebn
    where   substring(servan,0,4) = servicebn and 
            name <> testname
)
SELECT  service, name, total
FROM    recordsLIst
WHERE   rn <= 2

As a side note, this query has poor in performance because it requires FULL TABLE SCAN on every table. The reason is because of the join condition substring(servan,0,4)=servicebn. It doesn't use index.

Upvotes: 2

Related Questions