postgresql - Postgresql - 根据条件选择列
问题描述
在此查询中,“每日”case
将被一个变量替换。我无法使这个查询工作。我希望根据变量的值将日期列设置为一天、一个月、一周或一年。但它给了我各种错误..
- CASE 类型日期和双精度无法匹配
- “as”附近的语法错误
我究竟做错了什么?
select
case 'Daily'
when 'Daily' then DATE(to_timestamp(e.startts)) as "Date",
when 'Weekly' then DATE_PART('week',to_timestamp(e.startts)) as "Date",
when 'Monthly' then to_char(to_timestamp(e.startts), 'mm/yyyy') as "Date",
when 'Yearly' then to_char(to_timestamp(e.startts), 'yyyy') as "Date",
end
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"
解决方案
CASE ... END
是一个表达式。表达式必须具有明确定义的数据类型,因此 PostgreSQL 确保THEN
子句中的表达式具有相同的数据类型(或至少兼容的数据类型)。
text
在前两个分支中,您可能需要一个类型转换,可能是 to :
... THEN CAST (date(to_timestamp(e.startts)) AS text)
但在所有分支中使用会好得多to_char
——您需要的所有内容都有格式代码。
表达式可以没有别名,只有SELECT
orFROM
列表中的条目可以。所以你需要AS "Date"
在表达式的末尾追加CASE ... END
,而不是在中间的某个地方。
推荐阅读
- asp.net - 端口 454 和 455 上的 Azure HSTS 安全性
- python-3.x - Python中的文件路径和文件
- java - PrematureCloseException 的原因是什么?
- azure - 从 Azure 函数配置中删除机密
- python-3.x - 如何解决行/列的熊猫长度错误
- javalite - Maven Central 上 javalite 包 2.3.3 版的目标发布日期是什么?
- c - 长方体中的立方体
- bokeh - 如何在 Bokeh 中显示或隐藏图形线
- laravel - 将 laravel/Homestead 从“7.2.1”更新到“10.1.0”的问题
- oracle - 逻辑应用程序 oracle 获取行选择查询为列提供别名