1

我有一个有 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

任何帮助将非常感激

4

1 回答 1

2

如果你正在使用SQL Server 2005+,你可以使用Common Table ExpressionWindow 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

附带说明一下,此查询的性能很差,因为它需要FULL TABLE SCAN在每个表上。原因是由于加入条件substring(servan,0,4)=servicebn。它不使用索引。

于 2013-01-23T12:16:46.690 回答