2012-01-04 67 views
1

我不知道如何與一個變量做到這一點:TSQL幫助計算百分比

SELECT Count(distinct UserIP) 
FROM VisitorIP 
G0 

SELECT Country, Count(distinct UserIP) Visitors, Count(distinct UserIP) * 100/2865 Pct 
FROM VisitorIP group by country order by Visitors desc 

現在我想通過計數(不同USERIP)以上,以取代2865。

有一個說法:在IT中,最好的人誰知道10誰搜索!

任何線索的歡迎... 新年快樂,在那裏所有的怪才。

回答

3

使用變量:

DECLARE @userip_count int 

SELECT @userip_count = Count(distinct UserIP) 
FROM VisitorIP 

SELECT Country, Count(distinct UserIP) Visitors, Count(distinct UserIP) * 100/@userip_count Pct 
FROM VisitorIP group by country order by Visitors desc 
GO 

移動GO是必不可少這裏,爲了使變量保持作用域在第二個查詢使用。

+0

工程就像一個魅力與最小的變化,謝謝! – 2012-01-04 00:43:57

+0

很高興有幫助。 – philofinfinitejest 2012-01-04 00:45:10

0
SELECT Country, 
Count(distinct UserIP) Visitors, 
round(Count(distinct UserIP)/
       (SELECT Count(distinct UserIP) 
       FROM VisitorIP) * 100,2) Pct 
FROM VisitorIP 
group by country 
order by Visitors desc