create table TB_Cust(CustID int,CustName varchar(10),CustType int,Gender varchar(10))
insert into TB_Cust select 1,'小林' , 1   , '男'
union all select 2  ,'小芳'  ,2    ,'女'
union all select 3  ,'小新'  ,2    ,'男'
union all select 4  ,'小雄'  ,1    ,'男'
union all select 5  ,'小青'  ,2    ,'女'
union all select 6  ,'小李'  ,2    ,'男'   select 性别=Gender,
       客户总数=count(*),
       [(性别)百分比]=cast(cast((count(Gender)+0.0)/(select count(*) from TB_Cust) as dec(6,2)) as varchar)+'%',
       类型1=sum(case CustType when 1 then 1 else 0 end),
       类型2=sum(case CustType when 2 then 1 else 0 end),
       类型3=sum(case CustType when 3 then 1 else 0 end),
       类型4=sum(case CustType when 4 then 1 else 0 end),
       类型5=sum(case CustType when 5 then 1 else 0 end)
from TB_Cust
 group by Genderdrop table TB_Cust 

解决方案 »

  1.   


    Select 
    性别,
    Count(*),
    Count(*)*1.0/(Select Count(*) From TB_Cust) As [(性别)百分比],
    SUM(Case CustType When 1 Then 1 Else 0 End ) As 类型1,
    SUM(Case CustType When 2 Then 1 Else 0 End ) As 类型2,
    SUM(Case CustType When 3 Then 1 Else 0 End ) As 类型3,
    SUM(Case CustType When 4 Then 1 Else 0 End ) As 类型4,
    SUM(Case CustType When 5 Then 1 Else 0 End ) As 类型5
    From TB_Cust
    Group By 性别
      

  2.   

    select 性别=gender,客户总数=count(*),百分比=left(cast(count(*)*1.0/(select count(*) from tb_cust) as real),4),
    类型1=sum(case when custtype=1 then 1 else 0 end),
    类型2=sum(case when custtype=2 then 1 else 0 end),
    类型3=sum(case when custtype=3 then 1 else 0 end),
    类型4=sum(case when custtype=4 then 1 else 0 end),
    类型5=sum(case when custtype=5 then 1 else 0 end)
    from tb_cust group by gender