比较Postgres / Ruby中的日期与月份

时间:2015-01-28 05:24:46

标签: ruby postgresql

我的表格中有一个日期栏,我希望在某个月之后“过滤”/选择项目。因此,如果我有来自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'的第二部分,而不是做年> gt = = 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子句中使用的列?

1 个答案:

答案 0 :(得分:1)

此错误:column "year_month" does not exist发生,因为year_month别名定义了SELECT-list,并且在WHERE子句中无法引用此类别名。

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

有些数据库允许它,但有些数据库不允许,而PostgreSQL却没有。这是SQL引擎之间的许多可移植性危险之一。

对于问题中显示的查询,您甚至不需要WHERE子句中的to_char,因为正如第一条评论中所提到的,与日期的直接比较更简单,更多效率也很高。

当查询在SELECT列表中具有复杂表达式并且在WHERE子句中重复它看起来不对时,有时可能会重构将表达式移动到查询开头的子选择或WITH子句中。