问题描述
CREATE TABLE costs (
id SERIAL PRIMARY KEY,entry_date DATE,costs DECIMAL
);
INSERT INTO costs
(entry_date,costs)
VALUES
('2020-01-01','500'),('2020-02-01','325'),('2020-03-01','200'),('2020-04-01','400'),('2020-05-01','900'),('2020-06-01','700'),('2020-07-01',('2020-08-01','100'),('2020-09-01','300'),('2020-10-01','850'),('2020-11-01','470'),('2020-12-01','800');
预期结果:
date_list | costs
--------------|----------------------------
2020-05-01 | 29.03 (=900/31)
2020-05-02 | 29.03 (=900/31)
2020-05-03 | 29.03 (=900/31)
2020-05-04 | 29.03 (=900/31)
在表中,我将每月的费用分配给了每月的一天。 现在我想做以下事情:
- 将费用除以月份中的天数,即可得出每天的费用。
- 仅显示在查询的 WHERE-Clause 中选择的日期。
参考 this question 我试过这个查询:
SELECT
gs.entry_date,c.costs / date_part('day',date_trunc('month',gs.entry_date) + interval '1 month - 1 day') AS costs
FROM costs c
JOIN
generate_series('2020-05-01'::date,'2020-05-04'::date,interval '1 day') AS gs(entry_date)
ON date_trunc('month',gs.entry_date) = c.entry_date
查询在 Postgres
中有效,但在 Redshift
中出现此错误:
ERROR: function generate_series(date,date,interval) does not exist Hint: No function matches the given name and argument types. You may need to add explicit type casts.
我需要用什么函数来替换 generate_series
部分才能在 redshift
中获得相同的结果?
解决方法
Redshift 根本没有方便的日期生成功能。如果您的表足够大(并且应该在 Redshift 中),您可以在查询中生成一个:
WITH gs as (
SELECT '2020-05-01'::date + (ROW_NUMBER() OVER () - 1) * INTERVAL '1 DAY' as entry_date
FROM costs
LIMIT 4
)
SELECT gs.entry_date,c.costs / date_part('day',date_trunc('month',gs.entry_date) + interval '1 month' - interval '1 day') AS costs
FROM costs c JOIN
gs
ON date_trunc('month',gs.entry_date) = c.entry_date;
如果您有日历表或数字表,则可以改用它们。
注意:如果您在 StackOverflow 上询问有关 Redshift 的问题,您应该使用 Redshift 标签而不是 Postgres。两个数据库完全不同。