我面临从SQL中的数据(字符变化类型) >> InvoiceDate提取月份和年份的问题。我已经看到,MySQL函数的解决方案相对简单: DATEFROMPARTS,按照下面的代码,SQLpostgres中是不可用的。如何在Postgres中获得相同的结果DATA_PART函数,但同时需要将列"InvoiceDate“的数据类型更改为日期
Select
CustomerID,
min(InvoiceDate) first_purchase_date,
DATEFROMPARTS(year(min(InvoiceDate)), month(min(InvoiceDate)), 1) Cohort_Date从#online_retail_main组通过CustomerID进入#队列
产出:
Customer ID| first_purchase_date |Cohort_Date|
-----------+-------------------------+-----------+
12345 | 2010-12-20 15:47:00:00 | 2010-12-01|我试图使日期与年份和月份相一致,而将日期定为所有人的1天。
发布于 2022-10-29 16:09:28
假设一个有效的Postgres timestamp
select date_trunc('month', '2010-12-20 15:47:00.00'::timestamp)::date;
date_trunc
------------
12/01/2010
--or ISO format
set datestyle = 'ISO,MDY';
select date_trunc('month', '2010-12-20 15:47:00.00'::timestamp)::date;
date_trunc
------------
2010-12-01使用警棍将timestamp截断为一个月,这意味着这个月的第一个月。然后将(::date)转换为date类型。DateStyle只处理如何将值显示给用户。该值未存储格式化。
要做类似于在MySQL中所做的事情:
select make_date(extract(year from '2010-12-20 15:47:00.00'::timestamp)::integer, extract(month from '2010-12-20 15:47:00.00'::timestamp)::integer, 1);这里使用make_date、日期/时间函数和extract来构建date。
https://stackoverflow.com/questions/74245633
复制相似问题