SQL 中不存在的键值的 PIVOT

问题描述 投票:0回答:1

我有一张桌子

test_table
-------------------
key      value       
'a'      'apple'     
'b'      'ball'
'c'       null
'd'       ''

我需要通过以下方式进行旋转!测试表中不存在

e
f
的键 但我希望
e
f
出现在数据透视表中,且值不可用

我想旋转 a、b、c、d、e、f,但在这种情况下任何键值都可能丢失

e
f
丢失

 pivot_table
 ------------------------------------
    a        b       c      d      e         f
  'apple'  'ball'  null          'N/A'     'N/A'
  
sql oracle pivot azure-databricks
1个回答
0
投票

我在 PySpark 中尝试了以下操作:

  • 导入 PySpark 模块,用于创建 Spark 应用程序,以及
    StringType
    StructType
    StructField
    来定义 DataFrame 的架构。
  • 包含两列(“key”和“value”)的示例 (smpl_data) 和一个指定每列数据类型的架构 (smp_schema)。
  • 使用提供的示例数据和架构创建名为 dilip_test_df 的 PySpark DataFrame。
  • 使用一些附加数据创建另一个名为additional_df 的DataFrame。
  • 联合操作用于将两个 DataFrame(dilip_test_dfadditional_df)组合成一个名为 dilip_combined_df 的新 DataFrame。
  • 接下来,通过虚拟键对组合的 DataFrame 进行分组,然后使用“键”值作为列来旋转数据。使用的聚合函数是first,它取第一个非空值。
  • 然后,特定列('a'、'b'、'd'、'e'、'f')中的缺失值将用字符串 'N/A' 填充。
from pyspark.sql import SparkSession
from pyspark.sql.types import StringType, StructType, StructField
smpl_data = [('a', 'apple'),
             ('b', 'ball'),
             ('c', None),
             ('d', '')]
smp_schema = StructType([
    StructField("key", StringType(), True),
    StructField("value", StringType(), True)
])
dilip_test_df = spark.createDataFrame(smpl_data, schema=smp_schema)
additional_data = [('e', None), ('f', None)]
additional_df = spark.createDataFrame(additional_data, schema=smp_schema)
dilip_combined_df = dilip_test_df.union(additional_df)
dilip_pivoted_df = (dilip_combined_df
                    .groupBy()
                    .pivot("key", ["a", "b", "c", "d", "e", "f"])
                    .agg({"value": "first"}))
dilip_pivoted_df = dilip_pivoted_df.na.fill('N/A', subset=['a', 'b', 'd', 'e', 'f'])
dilip_pivoted_df.show(truncate=False)
+-----+----+----+---+---+---+
|a    |b   |c   |d  |e  |f  |
+-----+----+----+---+---+---+
|apple|ball|NULL|   |N/A|N/A|
+-----+----+----+---+---+---+
© www.soinside.com 2019 - 2024. All rights reserved.