对行进行分组后,如何在返回值中包含组的最大值?
例如,如果我有这些数据:
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
的最大值添加到返回值?
答案 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)