sql - Mode-within-group equivalent in Presto
问题描述
In Postgres, the following query outputs the most-frequently-purchased cheese for each customer:
SELECT
customer,
MODE() WITHIN GROUP (ORDER BY "subcategory") AS "fav_cheese"
FROM dft
WHERE category = 'CHEESE'
GROUP BY
customer
This returns:
customer fav_cheese
1 cheddar # customer1's most-frequently-purchased cheese is cheddar
2 blue # customer2's most-frequently-purchased cheese is blue
3 shredded # customer3's most-frequently-purchased cheese is shredded
How to achieve the same output in Presto?
I've tried different methods with no success so far.
解决方案
作为一种解决方法,您可以使用直方图方法:
SELECT customer,
MAP_KEYS(hist)[
ARRAY_POSITION(MAP_VALUES(hist), ARRAY_MAX(MAP_VALUES(hist)))
] as fav_cheese
FROM (
SELECT customer, histogram(subcategory) as hist
FROM dft
WHERE category = 'CHEESE'
GROUP BY customer
) as f
推荐阅读
- android - TreeMap 未在某些设备上对元素进行排序
- python - 命令“python --verson”使用“awk”提取版本号
- mysql - 如何提高 SQL 计数性能?
- c# - Xamarin 形成 CFB 通知:如何在注册设备后刷新令牌?
- html - 为什么我的站点在 Dreamweaver 中预览时与发布时看起来不同?
- python-3.x - 为多个测试用例运行 while 循环,其中用例数量未知
- amazon-web-services - 具有自定义域和 CORS 的 AWS API Gateway
- c++ - 指向没有变量的方法的指针,这段代码是如何工作的?
- database - 如何将此代码存储在 Laravel 中。没有错误,没有存储
- scala - 使用 ChainBuilder 定义用户流的最佳方法是什么?