表一: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")这样好像不行啊

解决方案 »

  1.   

    select 
    (select count(id) from tab1 where name="xx")/(select count(id) from tab2 where name="xx")???  除数要判断是否为0
      

  2.   


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

  3.   


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

  4.   

    CREATE TABLE [dbo].[tb](
    [id] [int] NULL,
    [code] [decimal](18, 2) NULL
    ) ON [PRIMARY]GOINSERT INTO [DBText].[dbo].[tb]
               ([id]
               ,[code])
         VALUES
               (<id, int,>
               ,<code, decimal(18,2),>)
    GOCREATE TABLE [dbo].[tbs](
    [id] [int] NULL,
    [path] [varchar](100) NULL
    ) ON [PRIMARY]GOINSERT INTO [DBText].[dbo].[tbs]
               ([id]
               ,[path])
         VALUES
               (<id, int,>
               ,<path, varchar(100),>)
    GOselect  
     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 行受影响)
      

  5.   

    select cast(
           (select count(id) from tab1 where name="xx")*100.0
           /
           (select count(id) from tab2 where name="xx")
           as decimal(18,2))