2010-01-23 60 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