如何从直方图中select对应最高值的key?

How to select the key corresponding to highest value from histogram map?

我正在使用 histogram() 函数 https://prestodb.github.io/docs/current/functions/aggregate.html

它"Returns a map containing the count of the number of times each input value occurs."

结果可能如下所示:

{ORANGES=1, APPLES=165, BANANAS=1}

是否有函数可以 return APPLES 给定上述输入?

XY问题?

精明的 reader 可能会注意到 histogram() 的最终结果与我正在尝试做的事情相结合,将等同于神秘的 Mode Function,它存在于教科书中,但不存在于现实世界的数据库引擎中。

这是我此时的完整查询。我正在为每个 upper(address),zip 元组寻找最常出现的 upper(cmplx) 值:

select * from (select upper(address) as address, zip, 
               (SELECT max_by(key, value) 
                FROM unnest(histogram(upper(cmplx))) as t(key, value)),
               count(*) as N
from apartments 
group by upper(address), zip) t1
where N > 3
order by N desc;

错误...

SYNTAX_ERROR: line 2:55: Constant expression cannot contain column references

您可以将您从 histogram 获得的 map 转换为具有 map_entries. Then you can UNNEST that array to a relation and you can call max_by 的数组。请看下面的例子:

SELECT max_by(key, value) FROM (
    SELECT map_entries(histogram(clerk)) as entries from tpch.tiny.orders
)
CROSS JOIN UNNEST (entries) t(key, value);

编辑:

如@Alex R 所述,您还可以将 histogram 结果直接传递给 UNNEST:

SELECT max_by(key, value) FROM ( 
    SELECT histogram(clerk) as histogram from tpch.tiny.orders ) 
CROSS JOIN UNNEST (histogram) t(key, value);

在您的问题中,查询部分 (SELECT max_by(key, value) FROM unnest(histogram(upper(cmplx)) 是一个尚未支持的相关子查询。但是,您看到的错误具有误导性。 IIRC Athena 使用 Presto 0.172,此错误报告已在 0.183 中修复(参见 https://docs.starburstdata.com/latest/release/release-0.183.html - 那是在 2017 年 7 月,顺便说一句 map_entries 也在 0.183 中添加)

这是我用来从任意映射中获取对应于最大值的键的方法:

MAP_KEYS(mapname)[
                ARRAY_POSITION(
                    MAP_VALUES(mapname),
                    ARRAY_MAX(MAP_VALUES(mapname))
                )
            ]

用直方图代替 'mapname'。

不确定这个解决方案在计算上与其他答案相比如何,但我确实发现它更容易阅读。