【问题标题】:How to fetch only n number of rows in subquery to compare the fetched columns to a main query (in oracle sql)如何在子查询中仅获取 n 行以将获取的列与主查询进行比较(在 oracle sql 中)
【发布时间】:2022-01-25 06:23:03
【问题描述】:

我想获取最后三张发票的付款到期日期并将其与付款日期进行比较,并且只需要选择那些满足该条件的客户,我尝试实现如下示例,但它没有提供所需的输出。

我想检查所有最后三张发票的到期日期,并将其与所有最后三张发票的付款日期进行比较,因此按子查询中的最后修改对行进行排序,并尝试使用 rownum >= 3 对每个客户仅最后三个进行排序

但问题是我只得到三行,即 rownum >= 3 被应用于整个查询,而不仅仅是内部查询

select c.cust_node_id
  from payment pay
  inner join (select i.payment_due_date as pay_due_date,
                     cnh.customer_node_id as cust_node_id,
                     i.invoice_id as inv_id
                from invoice i
                inner join customer_node_history cnh
                  on i.customer_node_id = cnh.customer_node_id and
                     i.current_due = 0 and
                     rownum >= 3 and
                     cnh.customer_node_type_id = customer_node_type_id
                order by last_modified) c
    on pay.invoice_id = c.invoice_id and
       c.pay_due_date <= pay.payment_date;

【问题讨论】:

    标签: sql oracle nested-queries


    【解决方案1】:

    如果您希望找到至少 3 个付款日期超过到期日的客户,则加入表格并聚合并添加 HAVING 子句:

    select c.cust_node_id
    from   payment p
           inner join invoice i
           on     i.invoice_id   =  p.invoice_id
              and i.pay_due_date <= p.payment_date
           inner join customer_node_history cnh
           on     i.customer_node_id = cnh.customer_node_id
              and cnh.customer_node_type_id = customer_node_type_id
    GROUP BY c.cust_node_id
    HAVING COUNT(*) >= 3
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-29
      • 2023-03-17
      • 1970-01-01
      • 1970-01-01
      • 2016-03-14
      相关资源
      最近更新 更多