查询以提取与客户对应的先前订单日期?

时间:2016-08-02 18:05:48

标签: sql join reporting self-join cognos-bi

我有一个包含Customer表和Order表的模式。客户可以在多个日期下订单。对于与客户相对应的每个order_date,我需要先前的order_date。

假设客户下了4个订单,然后是最新订单(第4个订单) - 它必须提取当前order_date和之前的order_date(第3个订单)。对于客户下达的第三个订单,它必须将第3个order_date作为当前order_date和之前的order_date(第2个订单),如下所示。

我使用下面的查询来获取之前的order_date然后加入current_query来获取结果::

select customerid, orderid, order_date as previous_order_date
from (
    select c.customerid, o.orderid, o.order_date, 
        row_number() over (partition by c.customerid, o.orderid
                           order by o.order_date) rown
    from customers c join orders o on c.customerid = o.customerid
       ) a
where rown = 2

但问题是,我得到一个与customerid相对应的日期,而要求是 - 只是之前的order_date对应于客户的当前order_date。

任何建议都会有所帮助!感谢

2 个答案:

答案 0 :(得分:2)

尝试使用LAG()窗口函数customerid

select 
  c.customerid, o.orderid, o.order_date, 
  lag(o.order_date) over (partition by c.customerid order by o.order_date) AS prev_order_date
from customers c
join orders o on c.customerid = o.customerid

对于每个客户prev_order_date的最早订单将为空。

示例结果(不要介意orderid,它只是为了示例):

 customerid | orderid | order_date | prev_order_date
------------+---------+------------+-----------------
          1 |       6 | 2015-02-08 |
          1 |       2 | 2016-02-05 | 2015-02-08
          1 |       3 | 2016-02-08 | 2016-02-05
          1 |       1 | 2016-03-05 | 2016-02-08
          2 |       5 | 2016-07-01 |
          2 |       4 | 2016-07-08 | 2016-07-01

如果一个客户可以在不同的日期内放置相同的订单(很奇怪,但这似乎是您的情况),请在o.orderid条款中添加PARTITION BY

答案 1 :(得分:0)

不幸的是,当在SQL节点中用于报告时,LAG()不起作用。我尝试使用以下查询并获得所需的结果:

SELECT   c.customer_code, o.customer_sid, o.order_id, o.order_no,
         o.order_created_date,
         (SELECT MAX (o1.order_created_date)
            FROM d_customer c1 LEFT JOIN f_order o1
                 ON c1.customer_sid =
                                   o1.customer_sid
           WHERE c1.customer_sid = c.customer_sid
             AND o1.order_created_date < o.order_created_date
             AND EXISTS (SELECT 1
                           FROM f_invoice i
                          WHERE i.order_id = o1.order_id))
                                                   AS prev_order_created_date,
         t.financial_year, t.financial_month_no
    FROM d_customer c JOIN f_order o
         ON c.customer_sid = o.customer_sid
       AND c.customer_type = 'PATIENT'
       AND c.customer_country = 'UNITED STATES'
       AND o.customer_type = 'PATIENT'
       AND o.bill_to_country = 'UNITED STATES'
       AND o.order_status = 'SHIPPED'
       AND o.order_type = 'SALES'
       AND o.order_group = 'REVENUE'
     --  AND c.customer_code = '233379PT'
         LEFT JOIN d_time t ON t.time_sid = o.order_created_date_sid
ORDER BY order_created_date DESC