如何解决posgresql中更宽的数据集-SQL
我有下表:
CREATE TABLE my_table
(
the_debt_id varchar(6) NOT NULL,the_debt_paid date NOT NULL,the_debt_due date NOT NULL
)
INSERT INTO my_table
VALUES ('LMUS01','2019-05-03','2019-05-02'),('LMUS01','2019-06-03','2019-06-02'),'2019-07-01','2019-07-02'),('LMUS02','2019-05-07'),'2019-06-07','2019-06-07')
然后我提取了the_debt_paid
的最后一条记录和倒数第二条记录
select * from
(
SELECT *,row_number()
OVER (PARTITION BY the_debt_id ORDER BY the_debt_paid DESC) as rn
FROM my_table
)A where rn<=2
所以我有这个结果:
the_debt_id the_debt_paid the_debt_due
LMUS01 2019-07-01 2019-07-02
LMUS01 2019-06-03 2019-06-02
LMUS02 2019-06-07 2019-06-07
LMUS02 2019-05-03 2019-05-07
是否有一种方法可以通过分支the_debt_paid
来在SQL语句中获得更广泛的形式以获得预期的输出?
the_debt_id the_debt_paid_last the_debt_paid_next
LMUS01 2019-07-01 2019-06-03
LMUS02 2019-06-07 2019-05-03
我坚持使用以下代码:
select CASE
WHEN rn = 1 THEN the_debt_paid_last = the_debt_paid
WHEN rn = 2 THEN the_debt_paid_next = the_debt_paid
END
FROM (
select * FROM
(
SELECT *,row_number()
OVER (PARTITION BY the_debt_id ORDER BY the_debt_paid DESC) as rn
FROM my_table) A
WHERE rn<=2) final
解决方法
您可以进行条件聚合:
select
the_debt_id,max(the_debt_paid) filter(where rn = 1) the_debt_paid_last,max(the_debt_paid) filter(where rn = 2) the_debt_paid_next
from (
select
t.*,row_number() over (partition by the_debt_id order by the_debt_paid desc) as rn
from my_table t
) a
where rn <= 2
group by the_debt_id
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。