【问题标题】:SQL group-n-result (count, max, group)SQL group-n-result (count, max, group)
【发布时间】:2021-02-26 16:13:17
【问题描述】:

使用 SQL (Redshift) 我正在尝试计算并返回分组中每个项目的最大值。我尝试了许多示例,但没有一个产生我想要的输出。这是我所追求的一些示例数据和结果。

数据

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

我已经尝试了许多示例,但几个小时都没有到达任何地方,因此非常感谢您的帮助。

【问题讨论】:

    标签: sql group-by count max amazon-redshift


    【解决方案1】:

    我们可以在这里使用窗口函数:

    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 中,一路上,我们还拿起了一个行号,这次只按容器分区,按 count 降序排列。

    【讨论】:

    • 非常感谢蒂姆。这个答案与其他答案非常相似,但确实帮助了我! PM我,我可以表示感谢。 (不知道怎么做)
    猜你喜欢
    • 1970-01-01
    • 2021-02-25
    • 1970-01-01
    • 2010-11-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-09
    • 1970-01-01
    相关资源
    最近更新 更多