【问题标题】:SQL - Top 3 books sold each month (do NOT use window function) [closed]SQL - 每个月销量最高的 3 本书(不使用窗口函数)[关闭]
【发布时间】:2020-08-25 14:29:58
【问题描述】:

我有一个表调用 sales 有以下 5 列

sales - order_id, book_id, date, price, qty (i.e. # of books per book_id)

我想找出每个月销售额最高的 3 本书 (book_id)。我想避免使用 dense_rank() 函数。

【问题讨论】:

  • 在 Redshift 中没有其他合理的替代方案(我的意思是如果你一般排除窗口函数)。
  • @GordonLinoff 这是我在网上看到的一个面试题,面试官问了一个应该避免使用窗口函数的解决方案
  • @user12562215 。 . .替代解决方案在许多数据库中都有意义,但在 Redshift 中则不然。

标签: sql group-by sum amazon-redshift window-functions


【解决方案1】:

Window functins 绝对是这里的必经之路。这应该很简单:

select *
from (
    select
        date_trunc('month', date) date_month,
        book_id,
        sum(qty) total_qty,
        rank() over(partition by date_trunc('month', date) order by sum(qty) desc) rn
    from sales
    group by date_trunc('month', date), book_id
) t
where rn <= 3
order by date_month, rn

如果没有窗口函数,一种选择是使用带有相关聚合子查询的 having 子句:

select
    date_trunc('month', date) date_month,
    book_id,
    sum(qty) total_qty
from sales s
group by date_trunc('month', date), book_id
having sum(qty) >= (
    select sum(qty)
    from sales s1
    where date_trunc('month', s1.date) = date_trunc('month', s.date)
    group by book_id
    order by sum(qty) desc
    limit 1 offset 2
)
order by date_month, total_qty desc

【讨论】:

    猜你喜欢
    • 2013-06-14
    • 1970-01-01
    • 2021-01-25
    • 1970-01-01
    • 1970-01-01
    • 2012-02-06
    • 2020-01-28
    • 1970-01-01
    • 2017-08-18
    相关资源
    最近更新 更多