2017-07-15 5 views
1
DF.groupBy("id") 
    .agg(
    sum((when(upper($"col_name") === "text", 1) 
    .otherwise(0))) 
    .alias("df_count") 
    .when($"df_count"> 1, 1) 
    .otherwise(0) 
) 

Kann ich Aggregation für die Spalte, die als Alias ​​benannt wurde tun? h. wenn die Summe größer als eins ist, dann geben Sie 1 zurück. sonst 0Aggregation der abgeleiteten Spalte spark

Vielen Dank im Voraus.

Antwort

0

Ich denke, Sie ein anderes when.otherwise um das sum Ergebnis wickeln könnte:

val df = Seq((1, "a"), (1, "a"), (2, "b"), (3, "a")).toDF("id", "col_name") 
df.show 
+---+--------+ 
| id|col_name| 
+---+--------+ 
| 1|  a| 
| 1|  a| 
| 2|  b| 
| 3|  a| 
+---+--------+ 

df.groupBy("id").agg(
    sum(when(upper($"col_name") === "A", 1).otherwise(0)).alias("df_count") 
).show() 
+---+--------+ 
| id|df_count| 
+---+--------+ 
| 1|  2| 
| 3|  1| 
| 2|  0| 
+---+--------+ 


df.groupBy("id").agg(
    when(sum(when(upper($"col_name")==="A", 1).otherwise(0)) > 1, 1).otherwise(0).alias("df_count") 
).show() 
+---+--------+ 
| id|df_count| 
+---+--------+ 
| 1|  1| 
| 3|  0| 
| 2|  0| 
+---+--------+ 
+1

Perfect, danke Psidom – Babu

Verwandte Themen