简体   繁体   English

如何在给定条件 SQL 的情况下在分区中查找第 N 行?

[英]How to Find Nth Row in Partition Given a Condition SQL?

Hello I have the following tables:您好,我有以下表格:

Brand Columns: Brand_ID(Primary Key), Company Name品牌栏:Brand_ID(主键)、公司名称

Orders Columns: ORDER_ID(Primary Key), USER_ID, BRAND_ID(Foreign Key), DATE订单列:ORDER_ID(Primary Key), USER_ID, BRAND_ID(Foreign Key), DATE

I'm trying to get the 3rd order for each USER_ID, placed after 2018, if the order is from COMPANY_NAME X. I'm kind of lost on how to proceed.如果订单来自 COMPANY_NAME X,我正在尝试为每个 USER_ID 获取 2018 年之后下的第 3 个订单。我对如何进行有点迷茫。 I've tried using a window function, but I don't think it lets me use a WHERE function inside?我试过使用窗口函数,但我认为它不允许我在内部使用 WHERE 函数?

I have the following code:我有以下代码:

SELECT *
FROM (
    SELECT O.*,
        row_number() OVER (
            PARTITION BY USER_ID 
            WHERE DATE >= '2018/01/01'
            ORDER BY DATE
            ) as rank
    FROM Orders O
    ) O
JOIN Brands B ON O.BRAND_ID = B.BRAND_ID
WHERE O.rank = 3 AND B.COMPANY_NAME = 'X';

You want to filter in a where clause -- which is not part of the window function specification:您想在where子句中进行过滤——这不是窗口函数规范的一部分:

SELECT *
FROM (SELECT O.*,
             row_number() OVER (PARTITION BY USER_ID 
                                ORDER BY DATE
                               ) as rank
      FROM Orders O
      WHERE DATE >= '2018-01-01'
     ) O JOIN
     Brands B
     ON O.BRAND_ID = B.BRAND_ID
WHERE O.rank = 3 AND B.COMPANY_NAME = 'X';

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM