TSQL帮助计算百分比

时间:2012-01-04 00:23:53

标签: 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个人更了解的人更好!

任何线索欢迎...... 祝所有极客们新年快乐。

2 个答案:

答案 0 :(得分: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至关重要,以便变量保留在第二个查询中使用的范围内。

答案 1 :(得分: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