SQL Query为每个值选择前2

时间:2013-01-23 12:14:20

标签: sql tsql

我有一个包含3列的表,column1中的数据具有重复值,第3列包含总计,我想要做的是返回第1列中每个值的前2个总计。

我创建此表的查询如下:

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

任何帮助将不胜感激

1 个答案:

答案 0 :(得分:2)

如果您使用SQL Server 2005+,则可以使用公用表表达式窗口函数

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

作为旁注,此查询的性能较差,因为它在每个表上都需要FULL TABLE SCAN。原因是因为连接条件substring(servan,0,4)=servicebn。它不使用索引。