SQL 组-n-结果(计数、最大值、组)
SQL group-n-result (count, max, group)
使用SQL(红移)
我正在尝试计算 return 分组依据中每个项目的最大值。我尝试了很多示例,但 none 产生了我想要的输出。这是我想要的一些示例数据和结果。
数据
Container,fruit
box1, apple
box1, apple
box1, apple
box1, apple
box1, banana
box2, blueberry
box2, blueberry
box2, strawberry
box3, apple
box3, apple
box3, blueberry
查询结果
Container, fruit, count
box1, apple, 4
box2, blueberry,2
box3, apple, 2
我已经尝试了很多例子,几个小时都没有取得任何进展,所以非常感谢您的帮助。
我们可以在这里使用window函数:
WITH cte AS (
SELECT Container, fruit, COUNT(*) AS cnt,
ROW_NUMBER() OVER (PARTITION BY Container
ORDER BY COUNT(*) DESC) rn
FROM yourTable
GROUP BY Container, fruit
)
SELECT Container, fruit, cnt
FROM cte
WHERE rn = 1;
这里的逻辑是根据容器 和 水果进行基本的 GROUP BY
聚合查询,以查找每个组的计数。在 CTE 中,一路上,我们还选择了一个行号,这次仅按容器分区,按计数降序排列。
使用SQL(红移) 我正在尝试计算 return 分组依据中每个项目的最大值。我尝试了很多示例,但 none 产生了我想要的输出。这是我想要的一些示例数据和结果。
数据
Container,fruit
box1, apple
box1, apple
box1, apple
box1, apple
box1, banana
box2, blueberry
box2, blueberry
box2, strawberry
box3, apple
box3, apple
box3, blueberry
查询结果
Container, fruit, count
box1, apple, 4
box2, blueberry,2
box3, apple, 2
我已经尝试了很多例子,几个小时都没有取得任何进展,所以非常感谢您的帮助。
我们可以在这里使用window函数:
WITH cte AS (
SELECT Container, fruit, COUNT(*) AS cnt,
ROW_NUMBER() OVER (PARTITION BY Container
ORDER BY COUNT(*) DESC) rn
FROM yourTable
GROUP BY Container, fruit
)
SELECT Container, fruit, cnt
FROM cte
WHERE rn = 1;
这里的逻辑是根据容器 和 水果进行基本的 GROUP BY
聚合查询,以查找每个组的计数。在 CTE 中,一路上,我们还选择了一个行号,这次仅按容器分区,按计数降序排列。