1

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

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

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到返回值?

4

1 回答 1

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)
于 2017-04-12T20:40:36.680 回答