【问题标题】:Compare date to month-year in Postgres/Ruby在 Postgres/Ruby 中比较日期和月份
【发布时间】:2015-01-31 03:59:41
【问题描述】:

我的表格中有一个日期列,我想在某个年月之后“过滤”/选择项目。因此,如果我有 2010 年以后的数据,我有一个用户输入,将“2011-10”指定为他们想要查看数据的“最早日期”。

我当前的 SQL 如下所示:

select round(sum(amount), 2) as amount,
date_part('month', date) as month
from receipts join items
on receipts.item = items.item
where items.expense = ?
    and date_part('year', date)>=2014
    and funding = 'General'
group by items.expense, month, items.order
order by items.order desc;

在“where”的第二部分,我不想执行 year >= 2014,而是将to_char(date, 'YY-MMMM') >= ? 作为另一个参数,然后传入“2011-10”。但是,当我这样做时:

costsSql = "select round(sum(amount), 2) as amount,
to_char(date, 'YY-MMMM') as year_month
from receipts join items
on receipts.item = items.item
where items.expense = ?
    and year_month >= ?
    and funding = 'General'
group by items.expense, year_month, items.order
order by items.order desc"

并用我的两个参数调用它,我得到一个 postgres 错误:PG::UndefinedColumn: ERROR: column "year_month" does not exist

编辑:我将我的 YYYY-MM 字符串转换为日期并将其作为我的参数传入,它正在工作。但我仍然不明白为什么在 select 子句中创建该列后出现“列不存在”错误 - 有人可以解释一下吗?这样创建的列不能用在where子句中吗?

【问题讨论】:

  • 为什么不使用date >= ?::date 并传入2011-10-01

标签: ruby postgresql


【解决方案1】:

这个错误:column "year_month" does not exist 发生是因为year_month 是一个别名,定义了 SELECT 列表,而这样的别名不能在 WHERE 子句中引用。

这是基于 SELECT-list 在 WHERE 子句之后评估的事实,例如:Column alias in where clause? PG 开发人员的解释。

有些数据库仍然允许,有些则不允许,而 PostgreSQL 不允许。这是 SQL 引擎之间的众多可移植性危害之一。

在问题中显示的查询的情况下,您甚至不需要 WHERE 子句中的to_char,因为正如第一条评论中提到的,直接与日期比较也更简单、更有效.

当查询在 SELECT-list 中有一个复杂的表达式并且在 WHERE 子句中重复它看起来是错误的,有时它可能会被重构以将表达式移动到查询开头的子选择或 WITH 子句中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多