繁体   English   中英

计算红移中两个日期之间的精确月差

[英]Calculate exact month-difference between two dates in redshift

DB-小提琴

CREATE TABLE inventory (
    id SERIAL PRIMARY KEY,
    inventory_date DATE,
    product_name VARCHAR(255),
    product_value VARCHAR(255)
);

INSERT INTO inventory
(inventory_date, product_name, product_value)
VALUES 
('2020-10-19', 'Product_A', '400'),
('2020-10-22', 'Product_B', '400'),
('2020-11-20', 'Product_C', '900'),
('2020-11-25', 'Product_D', '300');

预期结果:

    product_name    |     months_in_inventory    |
--------------------|----------------------------|----------
    Product_A       |            2               | 
    Product_B       |            1               | 
    Product_C       |            1               | 
    Product_D       |            0               | 

我想通过计算months_in_inventoryinventory_date之间的差异来计算fixed_date
在示例中, fixed_date'2020-12-20' ,我正在使用它进行查询。
postgresSQL中,我能够通过来自这个问题的查询来达到预期的结果:

SELECT 
iv.product_name,

(EXTRACT(year FROM age('2020-12-20'::date, MAX(iv.inventory_date::date))) * 12 +
EXTRACT(month FROM age('2020-12-20'::date, MAX(iv.inventory_date::date)))
) AS months_in_inventory

FROM inventory iv
GROUP BY 1
ORDER BY 1;

但是,当我在redshift上运行此查询时出现错误:

ERROR: Specified types or functions (one per INFO message) not supported on Redshift tables.

我需要如何更改查询以使其在redshift上工作?

Redshift 不支持age() 使用months_between()

SELECT iv.product_name,
       FLOOR(MONTHS_BETWEEN('2020-12-20'::date, iv.inventory_date::date)) as months_in_inventory
FROM inventory iv
GROUP BY 1
ORDER BY 1; 

戈登林诺夫的回答是死的。 我只想为这篇文章的未来读者添加一个注释:

当您看到“错误:Redshift 表不支持指定的类型或函数(每条 INFO 消息一个)”时。 将其翻译为“错误:您仅使用了领导节点 function 和计算节点数据。使用不同的 function。”

这个问题在这里和我的咨询中不断出现。 我希望 AWS 能提供更有用的错误消息,并仅识别有问题的领导节点 function。 这一直是错误消息,并且围绕它的混乱仍在继续。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM