我试图获取表格中列的唯一值,并将其打印在其他列的旁边,例如sum,tablename,如下面的查询中所示。 下面显示的子查询是获取有效的多行,但为了将其放入列中,我需要将其展平为列表或文本,例如[1,2,1]。如何将此数据展平以适合如下所示的相同查询。我首选的方法是使用Spark SQL。请帮忙。
**Subquery**
(select distinct $field from tablename)
**Actual Code**
RDDdf.createOrReplaceTempView(“tablename”)
val x= RDDdf.schema.fieldNames
val dfs = x.map(field => spark.sql(s"select 'RDDdf' as TableName,
'$field'as column, sum($field) as Sum, (select distinct $field from
tablename) from tablename"))
**Expected output**
TableName | column | Sum | UniqueVal
----------+---------+-----+----------
RDDdf | a | 4 | 1,2,1
答案 0 :(得分:2)
使用内置函数collect_list:
select collect_list(value) from (select distinct($field) as value from tablename) as values
请注意,这对大型数据集来说非常慢