【问题标题】:I need a way to find if a row has a value, and if so then I need to group all rows based on another value我需要一种方法来查找一行是否有值,如果有,那么我需要根据另一个值对所有行进行分组
【发布时间】:2021-08-10 07:57:12
【问题描述】:

我需要一种方法来检查是否找到了某个值,例如“错误”,如果找到,则需要根据另一个值进行分组。我需要查找值 3,如果找到值 3,则需要对具有相同 ID 和 Value1 的所有行进行分组和标记。

注意:我在 SAS 工作。

请看下表:

|id|Value1|Value2          |Value3
|--| ---  | ---            | ---
|1 | Sta  |sta@example.com |Error
|2 |Danny |dany@example.com|
|3 |Elle  |elle@example.com|18
|1 | Sta  |sta@example.com |55
|2 |Danny |dany@example.com|
|3 |Elle  |elle@example.com|Error
|1 | Sta  |sta@example.com |67
|1 | Sta  |sta@example.com |57
|3 |Elle  |elle@example.com|12
|3 |Elle  |elle@example.com|15
|3 |Elle  |elle@example.com|12

我需要把上表变成这样:

|id|Value1|Value2          |Value3
|--| ---  | ---            | ---
|1 | Sta  |sta@example.com |Error
|2 |Danny |dany@example.com|NoError
|3 |Elle  |elle@example.com|Error

我试过 case when 然后按 ID 分组,但没有运气。任何帮助将不胜感激。干杯。

【问题讨论】:

  • 不清楚您的要求。您是否尝试查找 ID、VALUE1 和 VALUE2 的唯一值集,并根据该组是否有任何错误将 VALUE3 生成为 ERROR 或 NOERROR?
  • 是的!本质上,我试图找出该组是否有错误,如果他们有,那么我想将所有这些都标记为错误。

标签: sql sas proc-sql


【解决方案1】:

在基础 SAS 中:

** Find unique ID/value1/value2 combos with any error **;
proc sort data=have (where=(value3='Error')) out=any_error (keep=id value1 value2) nodupkey; by id value1 value2;

** Keep first occurrence of each ID/value1/value2 combination, assigning value3 to Error if any error in original data, else NoError **;
data want;
   merge have (keep=id value1 value2) any_error (in=in1); by id value1 value2;
   if first.id value1 value2;
   value3 = ifc(in1,'Error','NoError');
run;


【讨论】:

    【解决方案2】:

    您的描述令人困惑,但输出看起来像是您想按 ID、VALUE1 和 VALUE2 分组,然后测试该组中的任何观察是否在 VALUE3 中有错误。

    SAS 会将布尔表达式评估为 1/0 以判断真/假。因此,组上的布尔表达式的 MAX() 正在测试表达式是否为真。

    proc sql ;
    select id, value1, value2 
         , case when (max( value3='Error')) then 'Error' else 'NoError' end as Value3 
    from have
    group by id, value1, value2
    ;
    quit;
    

    结果:

          id  Value1    Value2                Value3
    -------------------------------------------------
           1  Sta       sta@example.com       Error
           2  Danny     dany@example.com      NoError
           3  Elle      elle@example.com      Error
    

    【讨论】:

      【解决方案3】:

      嗨。你可以使用 Row_Number

      Select ROW_NUMBER() OVER(Partition by Value3 ORDER BY Value1) AS Row_Number ,
      * from YourTable  
      

      【讨论】:

      • PROC SQL 不支持窗口函数,即使支持,也不清楚这将如何帮助解决问题。
      猜你喜欢
      • 1970-01-01
      • 2018-06-06
      • 2011-07-16
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 2016-09-17
      • 2012-11-22
      • 2013-08-16
      相关资源
      最近更新 更多