【问题标题】:count the values in one column by SQL - using SAS通过 SQL 计算一列中的值 - 使用 SAS
【发布时间】:2018-03-19 15:07:58
【问题描述】:

我有一个customer_noclass。 我想为每个客户从同一列计算比率。

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   

输出样本将是

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

【问题讨论】:

  • 请不要以图片形式发布示例数据,始终以格式化文本形式发布。
  • 对不起,我会修改的
  • 2 / 3 = 0.6666661的比例怎么变成0.75
  • 我把答案作为样本。我已经修改了问题。正确答案是 0.666
  • 你用什么代码得到 0.75 作为比率?您是在计算观察的数量还是出现的不同值的数量?或者您是否需要计算可能出现的不同值的数量?如果是最后一个,那么您需要一个可能值数量的来源,因为某些值可能不会出现在您的实际数据中。

标签: sql sql-server sas sas-macro


【解决方案1】:

您可以像这样在查询中计算比率:

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;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-12-05
      • 2013-06-21
      • 2019-11-07
      相关资源
      最近更新 更多