Simple SQL that I am stuck on

后端 未结 3 1715
礼貌的吻别
礼貌的吻别 2021-01-29 06:26

What percent of customers are reward members?

ID                 Reward Member
1                       y
2                       y
3                       n
4            


        
相关标签:
3条回答
  • 2021-01-29 07:02

    I would use conditional aggregation:

    select avg( case when rewardmember = 'y' then 1.0 else 0 end) as ratio
    from t;
    

    Some databases allow shorter syntax, such as:

    select avg( rewardmember = 'y' )
    from t;
    

    or:

    select avg( (rewardmember = 'y')::int )
    from t;
    
    0 讨论(0)
  • 2021-01-29 07:06

    You can use COUNT():

    select
      1.0 *
      count(case when reward_member = 'y' then 1 else 0 end)
      / count(*) 
    from t
    
    0 讨论(0)
  • 2021-01-29 07:23

    Count how many are members, divide by total number of customers and multiply by 100.

    SELECT sum(case when RewardMember = 'y' then 1 else 0 end)*100.0/count(*) as percentage
    FROM Customers
    
    0 讨论(0)
提交回复
热议问题