SQL - 总行的百分比

时间:2013-11-06 01:47:38

标签: sql sql-server tsql

我有这个问题:

SELECT 
Count(*) as Cnt, 
Category
FROM [MyDb].[dbo].[MyTable]
group by Category
order by Cnt

它给出了每个Category中的行数。现在我想添加一个第三列,它会给我Cnt / (total rows in this table)

我该怎么做?

2 个答案:

答案 0 :(得分:6)

作为一个注释,您实际上可以使用窗口函数通过一个查询执行此操作:

SELECT Count(*) as Cnt, Category,
       cast(Count(*) as float) / sum(count(*)) over () as ThirdColumn
FROM [MyDb].[dbo].[MyTable]
group by Category
order by Cnt

答案 1 :(得分:2)

你可以用子查询来做到这一点:

SELECT Count(*) as Cnt, Category, 
  (Cast(Count(*) as real) / cast((SELECT Count(*) FROM [MyDb].[dbo].[MyTable]) as  real)) AS [Percentage]
FROM [MyDb].[dbo].[MyTable]
group by Category
order by Cnt

或使用变量:

declare @total real;
select @total = count(*) from [MyDb].[dbo].[MyTable];

SELECT Count(*) as Cnt, Category, (Cast(Count(*) as real) / @total) AS [Percentage]
FROM [MyDb].[dbo].[MyTable]
group by Category
order by Cnt

我在两个示例中都将count(*)转换为real,以避免整数除法类型问题。

希望这会有所帮助 约翰