首页 > 解决方案 > Postgresql - 根据条件选择列

问题描述

在此查询中,“每日”case将被一个变量替换。我无法使这个查询工作。我希望根据变量的值将日期列设置为一天、一个月、一周或一年。但它给了我各种错误..

我究竟做错了什么?

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"

标签: postgresqlcase

解决方案


CASE ... END是一个表达式。表达式必须具有明确定义的数据类型,因此 PostgreSQL 确保THEN子句中的表达式具有相同的数据类型(或至少兼容的数据类型)。

text在前两个分支中,您可能需要一个类型转换,可能是 to :

... THEN CAST (date(to_timestamp(e.startts)) AS text)

但在所有分支中使用会好得多to_char——您需要的所有内容都有格式代码。

表达式可以没有别名,只有SELECTorFROM列表中的条目可以。所以你需要AS "Date"在表达式的末尾追加CASE ... END,而不是在中间的某个地方。


推荐阅读