3

我有这个查询:

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

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

我怎样才能做到这一点?

4

2 回答 2

9

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

SELECT Count(*) as Cnt, Category,
       cast(Count(*) as float) / sum(count(*)) over () as ThirdColumn
FROM [MyDb].[dbo].[MyTable]
group by Category
order by Cnt
于 2013-11-06T02:17:13.957 回答
3

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

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(*) 强制转换为实数,以避免整数除法类型问题。

希望这可以帮助约翰

于 2013-11-06T01:55:34.507 回答