以前在學這個函數的時候,上課睡着了,哈哈哈,沒注意聽,講一下agg函數的用法。
首先,你需要先知道他的使用場景,知道使用場景了你才能靈活的去運用它。
我們一般主要使用它做一下分組后的聚合操作與groupBy函數一起使用,也可以單獨使用對整體進行聚合操作。
下面給大家在網上找了一段非常不錯的代碼:
1 stuDF.groupBy("gender").agg(max("age"),min("age"),avg("age"),count("classId")).show() 2 //同樣也可以這樣寫 3 //stuDF.groupBy("gender").agg("age"->"max","age"->"min","age"->"avg","id"->"count").show() 4 5 stuDF.agg(max("age"),min("age"),avg("age"),count("classId")).show() 6 7 stuDF.groupBy("classId","gender").agg(max("age"),min("age"),avg("age"),count("classId")).orderBy("classId").show()
然后結果區別:
+------+--------+--------+------------------+--------------+ |gender|max(age)|min(age)| avg(age)|count(classId)| +------+--------+--------+------------------+--------------+ | F| 23| 20|21.333333333333332| 3| | M| 22| 16| 19.5| 4| +------+--------+--------+------------------+--------------+ +--------+--------+------------------+--------------+ |max(age)|min(age)| avg(age)|count(classId)| +--------+--------+------------------+--------------+ | 23| 16|20.285714285714285| 7| +--------+--------+------------------+--------------+ +-------+------+--------+--------+--------+--------------+ |classId|gender|max(age)|min(age)|avg(age)|count(classId)| +-------+------+--------+--------+--------+--------------+ | 1001| F| 20| 20| 20.0| 1| | 1001| M| 19| 19| 19.0| 1| | 1002| M| 16| 16| 16.0| 1| | 1003| M| 21| 21| 21.0| 1| | 1003| F| 23| 23| 23.0| 1| | 1004| F| 21| 21| 21.0| 1| | 1004| M| 22| 22| 22.0| 1|