从CockroachDB中的GROUP BY操作中选择最大值?

时间:2017-04-12 20:40:37

标签: sql greatest-n-per-group cockroachdb

对行进行分组后,如何在返回值中包含组的最大值?

例如,如果我有这些数据:

INSERT INTO orders (customer_id, total) 
VALUES 
(1, 19.99), 
(2, 19.99), 
(1, 5.99), 
(2, 25.99);

我知道我可以使用此查询返回每个客户:

SELECT customer_id FROM orders GROUP BY customer_id;

但是如何将orders.total的最大值添加到返回值?

1 个答案:

答案 0 :(得分:1)

CockroachDB支持此类关系的标准SQL语法。以下查询为每个customer_id生成一个结果,其中包含该客户的customer_id和最大total

SELECT x.customer_id, x.total
FROM orders AS x
JOIN (SELECT o.customer_id,
    MAX(total) AS max_total
    FROM orders o
    GROUP BY o.customer_id) y 
ON y.customer_id = x.customer_id
AND y.max_total = x.total
GROUP BY x.customer_id, x.total;

针对样本数据的结果如下:

+-------------+-------+
| customer_id | total |
+-------------+-------+
|           1 | 19.99 |
|           2 | 25.99 |
+-------------+-------+
(2 rows)