了解 postgresql 中的显式类型转换

Understanding explicit type casts in postgresql

WHEN 'H' = 'E' THEN CAST(DATE_PART('Year', now()) AS CHAR(4))+ '0101'

我想获取当前年份并将月份和日期添加到今年。当我 运行 查询时,我 运行 进入以下错误。有人以前经历过吗?

SQL Error [42883]: ERROR: operator does not exist: character + unknown Hint: No operator matches the given name and argument types. You might need to add explicit type casts.

您试图在文本中添加数值,这是不允许的。要创建日期,请使用 make_date:

SELECT 
  make_date(date_part('year', now())::int,01,01),
  make_date(EXTRACT(YEAR FROM now())::int,01,01),
  EXTRACT(YEAR FROM now())||'0101'; -- in case you just need a string 

 make_date  | make_date  | ?column? 
------------+------------+----------
 2021-01-01 | 2021-01-01 | 20210101

我觉得那个方法真的很神秘。两种选择:

WHEN 'H' = 'E' THEN TO_CHAR(NOW(), 'YYYY') || '0101'

WHEN 'H' = 'E' THEN TO_CHAR(DATE_TRUNC('YEAR', NOW()), 'YYYYMMDD')