![](/img/trans.png)
[英]postgresql/pgAdmin - accepting start_date & end_date arguments as input on query run
[英][postgresql - generate months from start_date and end_date base on total_x]
我在 postgresql 中有三列
不 | total_car_sales | 開始日期 | 結束日期 |
---|---|---|---|
1 | 5 | 2022 年 1 月 1 日 | 2022 年 8 月 3 日 |
2 | 1 | 2022 年 4 月 1 日 | 2022 年 7 月 3 日 |
3 | 3 | 2022 年 3 月 1 日 | 2022 年 5 月 3 日 |
4 | 7 | 2022 年 1 月 1 日 | 2022 年 7 月 3 日 |
5 | 56 | 2022 年 4 月 1 日 | 2022 年 4 月 25 日 |
6 | 3 | 2022 年 4 月 1 日 | 2022 年 8 月 4 日 |
這里的示例從 start_date No.1:“Jan-01-2022”到“August-03-2022”:我將只計算 2022 年 8 月,因此 2022 年 8 月的結果是 5。第 6 號結果是 2022 年 8 月是3。結果我想為整個表生成total_car_sales,如下所示:
幾個月 | total_car_sales |
---|---|
2022 年 1 月 | 0 |
2022 年 2 月 | 0 |
2022 年 3 月 | 0 |
2022 年 4 月 | 56 |
2022 年 5 月 | 3 |
2022 年 6 月 | 0 |
2022 年 7 月 | 8 |
2022 年 8 月 | 8 |
我曾嘗試使用 trunc_cate() 但它不適用於它對我的建議的任何幫助非常感謝
謝謝
列出月份 ( generate_series
) 並計算每個月份的總銷售額。
with the_table (no,total_car_sales,start_date,end_date) as
(
values
(1, 5, 'Jan-01-2022'::date, 'Aug-03-2022'::date),
(2, 1, 'April-01-2022', 'July-03-2022'),
(3, 3, 'March-01-2022', 'May-03-2022'),
(4, 7, 'Jan-01-2022', 'July-03-2022'),
(5, 56, 'April-01-2022', 'April-25-2022'),
(6, 3, 'April-01-2022', 'Aug-04-2022')
)
select
to_char(m, 'mon-yyyy') "month",
coalesce
(
(select sum(total_car_sales) from the_table where m = date_trunc('month', end_date)),
0
) total_car_sales
from generate_series ('2022-01-01', '2022-08-01', interval '1 month') m;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.