同一行Postgresql中每个用户的最后两条记录

时间:2017-06-06 12:13:01

标签: sql postgresql greatest-n-per-group

我有两个表Customer表和INVOICE表

CREATE TABLE main.CUSTOMER
(
CUSTOMER_ID     SERIAL          PRIMARY KEY,
NAME            VARCHAR(128)    NOT NULL,
BIRTH_DATE      DATE            NOT NULL,
CREATION_DATE   TIMESTAMP       NOT NULL    DEFAULT(NOW())
);

CREATE TABLE main.INVOICE
(
INVOICE_ID      SERIAL      PRIMARY KEY,
INVOICE_DATE    TIMESTAMP   NOT NULL,
AGENT_ID        BIGINT      NOT NULL,
AMOUNT          NUMERIC(18, 5) NOT NULL,
CUSTOMER_ID     BIGINT      NOT NULL,
FOREIGN KEY (CUSTOMER_ID) REFERENCES main.CUSTOMER (CUSTOMER_ID)
);

我如何获得每个客户的最后两个发票金额(在同一行)。

1 个答案:

答案 0 :(得分:0)

一种方法是使用row_number()

select c.*,
       max(case when seqnum = 1 then amount end) as amount_latest,
       max(case when seqnum = 2 then amount end) as amount_prev
from customer c join
     (select i.*,
             row_number() over (partition by customer_id order by invoice_date desc) as seqnum
      from invoices i
     ) i
     on c.customer_id = i.customer_id
where i.seqnum in (1, 2)
group by c.customer_id;  -- other columns are not needed because `customer_id` is unique