Condividi tramite


string_agg_distinct

Funzione di aggregazione: restituisce la concatenazione di valori di input distinti non Null, separati dal delimitatore. Alias di listagg_distinct.

Sintassi

import pyspark.sql.functions as sf

sf.string_agg_distinct(col=<col>)

# With delimiter
sf.string_agg_distinct(col=<col>, delimiter=<delimiter>)

Parametri

Parametro TIPO Description
col pyspark.sql.Column o str Colonna di destinazione su cui eseguire il calcolo.
delimiter pyspark.sql.Column, str o bytes Optional. Delimitatore per separare i valori. Il valore predefinito è None.

Restituzioni

pyspark.sql.Column: colonna per i risultati calcolati.

Esempi

Esempio 1: uso della funzione string_agg_distinct.

import pyspark.sql.functions as sf
df = spark.createDataFrame([('a',), ('b',), (None,), ('c',), ('b',)], ['strings'])
df.select(sf.string_agg_distinct('strings')).show()
+----------------------------------+
|string_agg(DISTINCT strings, NULL)|
+----------------------------------+
|                               abc|
+----------------------------------+

Esempio 2: Uso della funzione string_agg_distinct con un delimitatore.

import pyspark.sql.functions as sf
df = spark.createDataFrame([('a',), ('b',), (None,), ('c',), ('b',)], ['strings'])
df.select(sf.string_agg_distinct('strings', ', ')).show()
+--------------------------------+
|string_agg(DISTINCT strings, , )|
+--------------------------------+
|                         a, b, c|
+--------------------------------+

Esempio 3: uso della funzione string_agg_distinct con una colonna binaria e un delimitatore.

import pyspark.sql.functions as sf
df = spark.createDataFrame([(b'\x01',), (b'\x02',), (None,), (b'\x03',), (b'\x02',)],
                           ['bytes'])
df.select(sf.string_agg_distinct('bytes', b'\x42')).show()
+---------------------------------+
|string_agg(DISTINCT bytes, X'42')|
+---------------------------------+
|                 [01 42 02 42 03]|
+---------------------------------+

Esempio 4: Uso di string_agg_distinct funzione in una colonna con tutti i valori Nessuno.

import pyspark.sql.functions as sf
from pyspark.sql.types import StructType, StructField, StringType
schema = StructType([StructField("strings", StringType(), True)])
df = spark.createDataFrame([(None,), (None,), (None,), (None,)], schema=schema)
df.select(sf.string_agg_distinct('strings')).show()
+----------------------------------+
|string_agg(DISTINCT strings, NULL)|
+----------------------------------+
|                              NULL|
+----------------------------------+