SQL - 重用具有不同过滤条件的窗口函数分区

发布于 2025-01-15 10:35:36 字数 617 浏览 2 评论 0原文

我有一个包含以下字段的表 orders

order_id: varchar
user_id:  varchar
item_id:  varchar
datetime: timestamp
quantity: int

以下查询将帮助我找到每个 user_id 的最后一个项目,其中数量 > 10.

WITH ranked AS (
    SELECT *,
        row_number() OVER (PARTITION BY user_id ORDER BY datetime DESC)
    FROM orders
    WHERE quantity > 10
)
SELECT user_id, item_id, datetime FROM ranked where rn = 1

现在,不再考虑数量>的订单。 10,我想找到相同的信息,但具有不同的阈值,例如 20、50、100。

一种选择是另外 3 个不同的查询,每个阈值一个。然而,它看起来效率不高。有更好的查询吗?

谢谢。

P/S:我需要一个用于 SparkSQL 或 Postgres 的。不过,通用 SQL 就可以了。

I have a table orders with the following fields:

order_id: varchar
user_id:  varchar
item_id:  varchar
datetime: timestamp
quantity: int

The following query would help me find the last item by each user_id where the quantity is > 10.

WITH ranked AS (
    SELECT *,
        row_number() OVER (PARTITION BY user_id ORDER BY datetime DESC)
    FROM orders
    WHERE quantity > 10
)
SELECT user_id, item_id, datetime FROM ranked where rn = 1

Now, instead of considering orders with quantity > 10, I want to find the same information but with different thresholds, like 20, 50, 100.

One option is to have another 3 different queries, one for each threshold. However, it looks not efficient. Is there a better query?

Thanks.

P/S: I will need one for SparkSQL or Postgres. However, generic SQL is fine.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文