count the values in one column by SQL - using SAS

北慕城南 提交于 2019-12-24 18:51:44

问题


I have a customer_no and class. I would like to calculate ratio from the same column for each customer.

ratio= (number of secured/ total number classes)

customer_no        class  
1                  unsecured   
1                  secured   
1                  secured   
2                  unsecured   
2                  secured   
3                  secured   
3                  unsecured   
3                  secured   
3                  unsecured   

The output sample will be

customer_no   ratio   
1              0.666 
2              0.50  
3              0.50 
.       
.   
.  
20000      

回答1:


You can calculate ratio in a query like this:

select customer_no,
    (count(case when class = 'secured' then 1 end)     -- count if class is secured
    +0.0)                                              -- add by a double value to cast values to double to get scales
    / count(*) ratio                                   -- count of all class
from yourTable
group by customer_no;

SQL Fiddle Demo




回答2:


proc sql;
   create table want as  
   select customer_no   
   ,sum(case when class='secured' then 1 else 0 end)/count(customer_no) as ratio   
   from  WORK.ENQUIRY_30   
   group by customer_no;   
quit;


来源:https://stackoverflow.com/questions/46628955/count-the-values-in-one-column-by-sql-using-sas

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!