2012-01-04 114 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