2010-01-23 59 views
0

我有一个返回从表组(集群)的功能..如何ROW_NUMBER添加到表函数结果

create function dbo.ftAllClusters() returns table as return 
select distinct Cluster from Company 

现在我需要添加ROWNUMBER每个返回的行..

回答

1
SELECT Cluster, ROW_NUMBER() OVER(ORDER BY Cluster) AS RowNo 
FROM 
(
    SELECT DISTINCT Cluster 
    FROM Company 
) x 

或者......

SELECT Cluster, ROW_NUMBER() OVER (ORDER BY Cluster) AS RowNo 
FROM Company 
GROUP BY Cluster 
+0

第二个选择似乎更便宜(Interms性能比较的)..投票up – TonyP 2010-01-23 12:47:14

+0

我认为他们最终可能会得到相同的执行计划(很快/基本测试显示他们这样做)。但我认为第二个更简洁。 – AdaTheDev 2010-01-23 12:53:04

0

还有就是建立功能的SQL称为ROW_NUMBER()

编辑: 根据由 为了不失独特的功能发表评论你可以尝试SubSelet

create function dbo.ftAllClusters() returns table as return 
    Select 
     Cluster 
     ,(ROW_NUMBER() OVER (order by Cluster)) as RN 
    from (
     Select 
      distinct 
      ,Cluster 
      from Company) as Comp 

或者你可以尝试使用GROUP BY而不是Distinc的(我甚至认为这是有点快)

Select 
    Cluster 
    ,(ROW_NUMBER() OVER (order by Cluster)) as RN 
from Company 
group by Cluster 
+0

这个空隙DISTINCT运算符,因为ROW_NUMBER(),使不同的所有行.. – TonyP 2010-01-23 12:30:05

0

这里是我制定了解决方案,有没有更好的办法?

ALTER function dbo.ftAllClusters() returns table as return 
With CTE(comno) as 
(select distinct Cluster from company) 

select id=Row_number() over(order by comno),comno from cte