2013-02-13 50 views
0

你會怎麼做:計數不同條目通過一個新的列求和值

Tim ... 
Tim ... 
Henry ... 
Henry ... 
Henry ... 

我對第一列thatc ontains這些名稱的表,我很感興趣,添加一個新的列X,即應該有:

0.5 
0.5 
0.333 
0.333 
0.333 

計算第一列中不同條目的數量(如果要執行新列的總和)。謝謝!

回答

2

您可以使用下列內容:

select name, 
    1.0/count(name) over(partition by name) as X 
from yourtable 

SQL Fiddle with Demo

+0

非常感謝你,bluefeet,在我注意到你的答案之前,我已經嘗試了第一個答案變種,但你的確非常有趣,特別是我沒有使用「分區」,但幾次!我現在要試試這個! – Sam 2013-02-13 11:47:04

+0

偉大的解決方案,經過測試,如果表中包含多列,選擇可以參考幾個! – Sam 2013-02-13 11:53:22

+1

@Sam不客氣。關於'over()'的好處是你不必對它使用'group by'子句。 :) – Taryn 2013-02-13 11:53:41

1

請嘗試:

select 
[Name], 1.00/count(*) 
from YourTable 
group by [Name] 

樣品:

declare @testTable table (Name varchar(10)) 

insert into @testTable 
select 'A' UNION ALL 
select 'A' UNION ALL 
select 'A' UNION ALL 
select 'B' UNION ALL 
select 'B' 

SELECT 
    [Name], 1.00/count(*) 
FROM @testTable 
GROUP BY [Name] 
+0

非常感謝你,techdo!我試過了,它創造了奇蹟。 – Sam 2013-02-13 11:52:37

相關問題