SQL语句求助!两个表的count值相除

w521286 2012-01-04 04:44:06
表一:tab1
字段:id,name,sex...

表二:tab2
字段:id,name,sex...

要求:用一条sql查询出表一中name为 “xx”的人数占表二中name为 “xx” 的人数的百分比

(select count(id) from tab1 where name="xx")/(select count(id) from tab2 where name="xx")

这样好像不行啊
...全文
4831 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
w521286 2012-01-06
  • 打赏
  • 举报
回复
谢谢各位
dawugui 2012-01-05
  • 打赏
  • 举报
回复 1
select cast(
(select count(id) from tab1 where name="xx")*100.0
/
(select count(id) from tab2 where name="xx")
as decimal(18,2))
勿勿 2012-01-04
  • 打赏
  • 举报
回复
CREATE TABLE [dbo].[tb](
[id] [int] NULL,
[code] [decimal](18, 2) NULL
) ON [PRIMARY]

GO

INSERT INTO [DBText].[dbo].[tb]
([id]
,[code])
VALUES
(<id, int,>
,<code, decimal(18,2),>)
GO



CREATE TABLE [dbo].[tbs](
[id] [int] NULL,
[path] [varchar](100) NULL
) ON [PRIMARY]

GO

INSERT INTO [DBText].[dbo].[tbs]
([id]
,[path])
VALUES
(<id, int,>
,<path, varchar(100),>)
GO



select
cast(cast((
( (select cast( COUNT(*) as decimal(18, 4)) from tbs) /nullif((select cast(COUNT(*)as decimal(18, 4)) from tb ),0))

*100) as decimal(18, 2)) as varchar(50)) +'%'
as 个数百分比


个数百分比
---------------------------------------------------
14.29%

(1 行受影响)


snbxp 2012-01-04
  • 打赏
  • 举报
回复

select (select count(1)*1.0 from tb1 where name='xx')/(select count(1) from tb2 where name='xx')

rucypli 2012-01-04
  • 打赏
  • 举报
回复
[Quote=引用 2 楼 geniuswjt 的回复:]
SQL code

select
(select count(id) from tab1 where name='xx')/
nullif((select count(id) from tab2 where name='xx'),0)
[/Quote]1
geniuswjt 2012-01-04
  • 打赏
  • 举报
回复

select
(select count(id) from tab1 where name='xx')/
nullif((select count(id) from tab2 where name='xx'),0)

AcHerat 元老 2012-01-04
  • 打赏
  • 举报
回复
select
(select count(id) from tab1 where name="xx")/(select count(id) from tab2 where name="xx")

??? 除数要判断是否为0。。。

34,590

社区成员

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

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