PostgreSQL按变量动态返回日期维度时CASE语句报错如何解决
问题原因分析
- 语法错误(syntax error near "as")的原因:
- CASE表达式是一个完整的计算字段,只能在整个CASE语句闭合后统一设置别名,不能在每个when分支内单独加
as "Date" - 每个when分支末尾多了冗余逗号,同时CASE语句结束后和
sum(e.checked)之间缺少逗号分隔两个查询字段
- CASE表达式是一个完整的计算字段,只能在整个CASE语句闭合后统一设置别名,不能在每个when分支内单独加
- 类型不匹配错误(CASE types date and double precison cannot be matched)的原因:
CASE语句要求所有分支的返回值类型必须兼容,你的四个分支返回类型分别是DATE、双精度浮点数、字符串、字符串,类型不统一导致数据库无法解析。
修正方案
所有分支统一转为字符串类型,调整别名位置,修正语法符号即可正常运行,示例如下:
select case :time_dimension -- 此处替换为你的变量,可传入'Daily'/'Weekly'/'Monthly'/'Yearly' when 'Daily' then to_char(to_timestamp(e.startts), 'yyyy-mm-dd') when 'Weekly' then DATE_PART('week',to_timestamp(e.startts))::varchar when 'Monthly' then to_char(to_timestamp(e.startts), 'mm/yyyy') when 'Yearly' then to_char(to_timestamp(e.startts), 'yyyy') end as "Date", sum(e.checked) from entries e WHERE e.startts >= date_part('epoch', '2020-10-01T15:01:50.859Z'::timestamp)::int8 and e.stopts < date_part('epoch', '2021-11-08T15:01:50.859Z'::timestamp)::int8 group by "Date"
内容的提问来源于stack exchange,提问作者sharkyenergy
相关产品推荐
相关产品推荐

