求一sql语句select出列的百分比

gonguui1982 2013-04-09 11:31:37
表A
ID Name num
1 小明 23
2 小刚 33
3 小红 44

求每个人num的数量占总数量的百分比
查询结果

name per
小明 0.23
小刚 0.33
小红 0.44
...全文
10178 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
中国风 2013-04-09
  • 打赏
  • 举报
回复
sql05以上版本用3楼方法效率比较高
中国风 2013-04-09
  • 打赏
  • 举报
回复

declare @A table([ID] int,[Name] nvarchar(2),[num] int)
Insert @A
select 1,N'小明',23 union all
select 2,N'小刚',33 union all
select 3,N'小红',44
 
Select a.[Name],cast(a.[num]*1.0/sum(a.[num])over() as numeric(8,2)) as per 
from @A as a
/*
Name	per
小明	0.23
小刚	0.33
小红	0.44
*/
中国风 2013-04-09
  • 打赏
  • 举报
回复
use Tempdb
go
--> --> 
 
declare @A table([ID] int,[Name] nvarchar(2),[num] int)
Insert @A
select 1,N'小明',23 union all
select 2,N'小刚',33 union all
select 3,N'小红',44
 
Select a.[Name],cast(a.[num]*1.0/b.[num] as numeric(8,2)) as per 
from @A as a,(select sum([num]) as [num] from @A) as b
/*
Name	per
小明	0.23
小刚	0.33
小红	0.44
/
  • 打赏
  • 举报
回复
select id,Name,num=cast(num*1.0/(select SUM(num) from tb) as decimal(28,2)) from tb
pard521 2013-04-09
  • 打赏
  • 举报
回复
select id,Name,num=cast(num*1.0/(select SUM(num) from 表A) as decimal(28,2)) from 表A

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧