【问题标题】:similar to groupByKey() in Spark but using SQL queries类似于 Spark 中的 groupByKey() 但使用 SQL 查询
【发布时间】:2021-03-15 00:26:20
【问题描述】:

我试着做

 ID    CATEGORY  VALUE
'AAA'    'X'      123
'AAA'    'Y'      456
'BBB'    'X'      321
'BBB'    'Y'      654

进入

 ID     VALUE_X   VALUE_Y
'AAA'     123       456
'BBB'     321       654

仅使用 SQL 查询。 这有点类似于在 pyspark 中使用 groupByKey()。

有没有办法做到这一点?

【问题讨论】:

    标签: sql postgresql pyspark apache-spark-sql


    【解决方案1】:

    只需使用条件聚合。一种方法是:

    select id,
           max(case when category = 'X' then value end) as x_value,
           max(case when category = 'Y' then value end) as y_value
    from t
    group by id;
    

    在 Postgres 中,这将使用标准的 filter 子句来表述:

    select id,
           max(value) filter (where category = 'X'),
           max(value) filter (where category = 'Y')
    from t
    group by id;
    

    【讨论】:

    • 为什么我们需要一个最大值?
    • @jginso7 。 . .你需要一个聚合函数,max() 很方便,因为它适用于所有类型。
    • 您好,还有一个问题... 什么是某些 ID 对 CATEGORY 没有价值?比如说,ID 'CCC' 只有 CATEGORY 'X' VALUE '123',但没有其他行。为此我想要CCC 123 0
    • 如果没有key,则值为NULL。您可以将表达式包装在coalesce()coalesce(max(value) filter (where category = 'Y'), 0)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多