sql数据统计的问题

rodking 2008-03-31 06:37:06
现有两个关联表,CustomerID为关联列
表1结构:
CustomerID,CompanyId,.....
12 YA
13 YA
14 YA
15 YC
16 YD

表2结构:
CustomerID,Disabled
12 0 (未启用)
14 1
15 1

现要统计分公司(CompanyId)启用的客户的数量,分公司客户总数,启用客户所占比例,用分公司分组。
结果类似:
启用数量 总数 所占比例 分公司
2 3 66.67% YA
1 1 100% YC



请问这样的sql语句该怎么写?对于高手来说,应该很简单的,多谢
...全文
64 2 打赏 收藏 转发到动态 举报
写回复
用AI写文章
2 条回复
切换为时间正序
请发表友善的回复…
发表回复
pt1314917 2008-03-31
  • 打赏
  • 举报
回复

declare @t1 table(customerid int,companyid varchar(10))
insert into @t1 select 12,'YA'
insert into @t1 select 13,'YA'
insert into @t1 select 14,'YA'
insert into @t1 select 15,'YC'
insert into @t1 select 16,'YD'

declare @t2 table(companyid int,Disabled int)
insert into @t2 select 12,0
insert into @t2 select 14,1
insert into @t2 select 15,1

select
起用数量=sum(case Disabled when 1 then 1 else 0 end),
总数=count(1),
所占比例=ltrim(cast(sum(case Disabled when 1 then 1 else 0 end)*100.00/count(1) as numeric(5,2)))+'%',
分公司=a.companyid
from @t1 a,@t2 b
where a.customerid=b.companyid
group by a.companyid
中国风 2008-03-31
  • 打赏
  • 举报
回复
select
cast(Disabled as int) as 启用数量,--bit时要转换
count(1) as 总数,
ltrim(str(cast(Disabled as decimal(18,5))/count(1),18,2))+'%' as 所占比例,
b.CompanyId as 分公司
from
t1 a
join
t2 b on a.CustomerID=b.CustomerID
group by b.CompanyId

34,576

社区成员

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

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