SQL - 总行的百分比(SQL - percentage of total rows)

2019-10-18 22:34发布

我有这个疑问:

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

这让我在每个计算行的Category 。 现在,我想补充的第三列,这将使我Cnt / (total rows in this table)

我怎样才能做到这一点?

Answer 1:

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

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(*)作为真正在这两个例子中,以避免整数分型的问题。

希望这有助于约翰



Answer 2:

作为一个说明,你其实可以用一个查询使用窗口函数做到这一点:

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


文章来源: SQL - percentage of total rows