我找到了一些可以讓我在這里和這里接近的答案,但不完全是我想要的。
這是示例資料集
CREATE TABLE invoices
(
"start" date,
"end" date,
custid int,
amt float
);
INSERT INTO invoices
VALUES ('2021-02-01', '2022-01-31', 1, 10),
('2021-03-01', '2021-03-31', 2, 20)
;
select * from invoices
| 開始 | 結尾 | 卡斯蒂德 | 上午 |
|---|---|---|---|
| 2021-02-01 | 2022-01-31 | 1 | 10 |
| 2021-03-01 | 2021-03-31 | 2 | 20 |
理想的輸出將為每個客戶生成系列,如下表所示
| 月 | 卡斯蒂德 | 上午 |
|---|---|---|
| 2021-02-28 | 1 | 10 |
| 2021-03-31 | 1 | 10 |
| 2021-04-30 | 1 | 10 |
| 2021-05-31 | 1 | 10 |
| 2021-06-30 | 1 | 10 |
| 2021-07-31 | 1 | 10 |
| 2021-08-31 | 1 | 10 |
| 2021-09-30 | 1 | 10 |
| 2021-10-31 | 1 | 10 |
| 2021-11-30 | 1 | 10 |
| 2021-12-31 | 1 | 10 |
| 2022-01-31 | 1 | 10 |
| 2021-03-31 | 2 | 20 |
我假設這將需要該generate_series功能,但很確定如何進行。
編輯:在標題中拼出 MRR,所以我們都在同一頁上。
編輯 2:下面的代碼塊似乎有效,但仍然對其他可能更有效的方法非常感興趣
CREATE TABLE invoices
(
"start" date,
"end" date,
custid int,
amt float
);
INSERT INTO invoices
VALUES ('2021-02-01', '2022-01-31', 1, 10),
('2021-03-01', '2021-03-31', 2, 20)
;
WITH cal AS ( -- calender table
SELECT generate_series('2021-02-01'::date, '2022-01-31'::date , '1 month'::interval)::date dt
)
SELECT
a.custid, a.amt
,a.start
,a.end
,c.dt
FROM cal c
CROSS JOIN invoices a
where a.start <= c.dt and a.end >=c.dt
order by a.custid, c.dt
;
SQL小提琴
uj5u.com熱心網友回復:
用于generate_series創建月份表:
SELECT (s.d '1 month')::date - 1 AS month,
i.custid,
i.amt
FROM invoices AS i
CROSS JOIN LATERAL generate_series(
i.start::timestamp,
i.end::timestamp,
'1 month'
) AS s(d)
ORDER BY i.custid, s.d;
month │ custid │ amt
════════════╪════════╪═════
2021-02-28 │ 1 │ 10
2021-03-31 │ 1 │ 10
2021-04-30 │ 1 │ 10
2021-05-31 │ 1 │ 10
2021-06-30 │ 1 │ 10
2021-07-31 │ 1 │ 10
2021-08-31 │ 1 │ 10
2021-09-30 │ 1 │ 10
2021-10-31 │ 1 │ 10
2021-11-30 │ 1 │ 10
2021-12-31 │ 1 │ 10
2022-01-31 │ 1 │ 10
2021-03-31 │ 2 │ 20
(13 rows)
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/422483.html
標籤:
