【问题标题】:Postgresql - select column based on conditionPostgresql - 根据条件选择列
【发布时间】:2024-01-10 22:13:01
【问题描述】:

在此查询中,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"

【问题讨论】:

    标签: postgresql case


    【解决方案1】:

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

    您需要在前两个分支中进行类型转换,可能是text

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

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

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

    【讨论】: