【问题标题】:Last two record for each user in same row Postgresql同一行中每个用户的最后两条记录 Postgresql
【发布时间】:2017-06-06 12:13:00
【问题描述】:

我有两张表 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)
);

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

【问题讨论】:

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


    【解决方案1】:

    一种方法是使用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
    

    【讨论】:

      猜你喜欢
      • 2022-10-14
      • 1970-01-01
      • 2021-11-04
      • 1970-01-01
      • 1970-01-01
      • 2020-04-09
      • 2020-10-01
      • 1970-01-01
      • 2018-06-28
      相关资源
      最近更新 更多